我正在尝试使用C#进行XML序列化时更改根元素的名称。
它总是采用类名而不是我尝试设置的名称。
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; }
}
}
结果
<?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>
它不会将其更改为WildAnimal。我不确定原因。我是从教程中获取的。
编辑 @Marc
谢谢。我现在明白你正在做什么,只是看起来很奇怪,你需要在它周围加一个包装器。 我还有一个问题,如果我想要制作这种格式,会发生什么
<root>
<element>
<name></name>
</element>
<anotherElement>
<product></product>
</anotherElement>
</root>
那就像嵌套元素一样。我是否需要为第二部分创建一个新类,然后将其放入包装类中?
product
一个anotherElement
,还是一个带有很多product
元素的单一anotherElement
。对于后者:[XmlArray]
/[XmlArrayItem]
- 否则是的:需要第二个类型。 - Marc Gravell