cho*_*bo2 9 c# xml xml-serialization
我正在尝试使用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>
就像一个嵌套元素.我是否必须为第二部分创建一个新类并将其粘贴到包装类中?
Mar*_*ell 14
在你的榜样,MyTest是没有根; 你想重命名数组吗?我会写一个包装器:
[XmlRoot("NameOfRootElement")]
public class MyWrapper {
    private List<MyTest> items = new List<MyTest>();
    [XmlElement("NameOfChildElement")]
    public List<MyTest> Items { get { return items; } }
}
static void Main() {
    MyTest test = new MyTest();
    test.Test = "gog";
    MyWrapper wrapper = new MyWrapper {
        Items = {  test }
    };
    SerializeToXML(wrapper);
}
static public void SerializeToXML(MyWrapper list) {
    XmlSerializer serializer = new XmlSerializer(typeof(MyWrapper));
    using (TextWriter textWriter = new StreamWriter(@"test.xml")) {
        serializer.Serialize(textWriter, list);
        textWriter.Close();
    }
}