Eldad

Getting rid of an array name in C # XML Serialization

I am trying to get this result when serializing XML:

<Root Name="blah"> <SomeKey>Eldad</SomeKey> <Element>1</Element> <Element>2</Element> <Element>3</Element> <Element>4</Element> </root> 

Or, in other words, I'm trying to contain an array inside the root element along with additional keys.

This is my rude attempt:

 [XmlRootAttribute(ElementName="Root", IsNullable=false)] public class RootNode { [XmlAttribute("Name")] public string Name { get; set; } public string SomeKey { get; set; } [XmlArrayItem("Element")] public List<int> Elements { get; set; } } 

And my serialization:

 string result; XmlSerializer serializer = new XmlSerializer(root.GetType()); StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { serializer.Serialize(sw, root); result = sw.ToString(); } 

However, this is my result (the namespace has been removed for clarity):

 <Root> <SomeKey>Eldad</SomeKey> <Elements> <Element>1</Element> <Element>2</Element> <Element>3</Element> </Elements> </Root> 

Is there a way to remove the "Elements" part?

+4
source share
2 answers

Use the XmlElement attribute in the array, this will instruct the serializer to serialize the elements of the array as children of the current element, and not create a new root element for the array.

 [XmlRootAttribute(ElementName="Root", IsNullable=false)] public class RootNode { [XmlAttribute("Name")] public string Name { get; set; } public string SomeKey { get; set; } [XmlElement("Element")] public List<int> Elements { get; set; } } 
+8
source

Thanks to Chris Taylor for answering my problem. Using the asmx web service, I got the following XML:

 <Manufacturers> <Manufacturer> <string>Bosch</string> <string>Siemens</string> </Manufacturer> </Manufacturers> 

I wanted to get the manufacturer names directly in the element, getting rid of the element like this:

 <Manufacturers> <Manufacturer>Bosch</Manufacturer> <Manufacturer>Siemens</Manufacturer> </Manufacturers> 

For someone else with the same problem, my code for this is (in VB.Net):

 <WebMethod()> _ Public Function GetManufacturers() As Manufacturers Dim result As New Manufacturers result.Manufacturer.Add("Bosch") result.Manufacturer.Add("Siemens") Return result End Function <XmlRoot(ElementName:="Manufacturers")> _ Public Class Manufacturers <XmlElement("Manufacturer")> _ Public Manufacturer As New List(Of String) End Class 
-1
source

All Articles