10

I'm trying to get to this result while 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 within the "root" element, alongside additional keys.

This is my crude 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 (Removed the namespace for clarity):

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

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

2 Answers 2

19

Use XmlElement attribute on the Array, this will instruct the serializer to serialize the array items as child elements 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; } 
} 
Sign up to request clarification or add additional context in comments.

1 Comment

With a Dictionary, this don't work because we need to manually browse items. :(
-1

Thanks to Chris Taylor for the answer to my problem too. Using an asmx web service, I was getting the following XML:

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

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

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

For anyone else with the same problem, my code to achieve this (in VB.Net) is:

<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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.