Tôi đang cố gắng thay đổi tên gốc khi thực hiện tuần tự hóa XML với C#.Làm thế nào để thay đổi tên gốc XML với XML serialization?
Nó luôn mang tên lớp chứ không phải tên tôi đang cố gắng đặt.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyTest test = new MyTest();
test.Test = "gog";
List<MyTest> testList = new List<MyTest>()
{
test
};
SerializeToXML(testList);
}
static public void SerializeToXML(List<MyTest> list)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<MyTest>));
TextWriter textWriter = new StreamWriter(@"C:\New folder\test.xml");
serializer.Serialize(textWriter, list);
textWriter.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
[XmlRootAttribute(ElementName = "WildAnimal", IsNullable = false)]
public class MyTest
{
[XmlElement("Test")]
public string Test { get; set; }
}
}
quả
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMyTest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyTest>
<Test>gog</Test>
</MyTest>
</ArrayOfMyTest>
Nó không thay đổi nó để WildAnimal. Tôi không chắc tại sao. Tôi đã nhận được điều này từ một hướng dẫn.
Sửa @ Marc
Cảm ơn. Bây giờ tôi thấy những gì bạn làm dường như quá kỳ quặc đến mức bạn phải làm một cái bọc quanh nó. Tôi có thêm một câu hỏi điều gì sẽ xảy ra nếu tôi muốn thực hiện định dạng này
<root>
<element>
<name></name>
</element>
<anotherElement>
<product></product>
</anotherElement>
</root>
như một yếu tố lồng nhau. Tôi sẽ phải tạo một lớp mới cho phần thứ hai và dính vào đó trong lớp trình bao bọc?
Chỉnh sửa lại; nó phụ thuộc vào việc bạn đặt một 'anotherElement' cho mỗi' product', hay một 'anotherElement' khác với việc mất các phần tử' product'. Đối với cái sau: '[XmlArray]'/'[XmlArrayItem]' - nếu không có: một kiểu thứ hai. –