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' 하나당'anotherElement'를 쓸지,'product' 엘리먼트를 잃어버린'anotherElement' 하나를 쓸지 여부에 달려 있습니다. 후자의 경우 :'[XmlArray]'/'[XmlArrayItem]'- 그렇지 않으면 yes : 두 번째 유형. –