I am trying to change the root name when doing XML serialization using C #.
It always accepts the name of the class, not the name I'm trying to set.
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; } } }
Result
<?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>
He does not change it to WildAnimal. I do not know why. I got this from a textbook.
Edit @ Mark
Thanks. Now I see what you are doing, it just seems strange that you have to wrap around it. I have one more question, what happens if I want to make this format
<root> <element> <name></name> </element> <anotherElement> <product></product> </anotherElement> </root>
like nested elements. Should I create a new class for the second part and stick to this in the wrapper class?
c # xml xml-serialization
chobo2
source share