我想在使用C#進行XML序列化時更改根名稱。如何使用XML序列化更改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。我不知道爲什麼。我從教程中獲得了這個。
編輯 @馬克
感謝。我現在看到你的行爲看起來很奇怪,你必須圍繞它做一個包裝。我還有一個問題會發生什麼,如果我想使這種格式
<root>
<element>
<name></name>
</element>
<anotherElement>
<product></product>
</anotherElement>
</root>
所以像一個嵌套的元素。我是否必須爲第二部分創建一個新課堂並將其固定在包裝類中?
重新編輯;它取決於你是否爲每個產品''另一個元素',或者單個'另一個元素'丟失了'product'元素。對於後者:'[XmlArray]'''[XmlArrayItem]' - 否則是:第二種類型。 – 2010-01-24 07:58:18