0

I have some XML files that look like this:

File "B156.xml"

<B156>
  <Customer>
    <Name>The Barn</Name>
    <Phone>0427825166</Phone>
  </Customer>
  <Orders>
    <Item>
      <Description>Black toner</Description>
      <Amount>$59.00</Amount>
    </Item>
  <Orders>
</B156>

File "B172.xml"

<B172>
  <Customer>
    <Name>Pixie Inc</Name>
    <Phone>0426553190</Phone>
  </Customer>
  <Orders>
    <Item>
      <Description>Colour toner</Description>
      <Amount>$79.00</Amount>
    </Item>
  <Orders>
</B172>

How do I use XmlSerializer in this case, considering the root element is dynamic and we cannot use XmlRoot("RootName") to specify it?

4
  • Can you not use LINQ to XML? Commented Aug 28, 2020 at 4:35
  • @silkfire I use XmlSerializer because there are a lot of properties that I need to serialise into domain class, examples above are simplified for brevity purpose. Commented Aug 28, 2020 at 5:48
  • 1
    considering your examples, cant you get the root element name from the file name itself? Commented Aug 28, 2020 at 7:58
  • @GurhanPolat I have no interest in getting the root element here. My problem is that XmlSerializer throws error if I don't specify a valid root, which in my case I can't because they are dynamic. (B156, B172 and so on) Commented Aug 28, 2020 at 12:30

1 Answer 1

1

You can try this,

CLASS OBJECT

[XmlRoot("root")]
public class CustomerOrder
{
    public Customer Customer { get; set; }

    [XmlArray("Orders")]
    [XmlArrayItem("Item")]
    public List<Order> Orders { get; set; }
}

public class Customer
{
    public string Name { get; set; }
    public string Phone { get; set; }
}

public class Order
{
    public string Description { get; set; }
    public string Amount { get; set; }
}

CHANGEROOT METHOD

    private static XmlDocument changeRoot(XmlDocument xmlDocument)
    {
        var newXmlDocument = new XmlDocument();
        var newRoot = newXmlDocument.CreateElement("root");
        newXmlDocument.AppendChild(newRoot);
        newRoot.InnerXml = xmlDocument.DocumentElement.InnerXml;

        return newXmlDocument;
    }

SERIALIZATION

        var xmlDocument = new XmlDocument();
        xmlDocument.Load("XMLFile1.xml");
        xmlDocument = changeRoot(xmlDocument);

        XmlSerializer serializer = new XmlSerializer(typeof(CustomerOrder));
        CustomerOrder result;

        using (TextReader reader = new StringReader(xmlDocument.InnerXml))
        {
            result = (CustomerOrder)serializer.Deserialize(reader);
        }
Sign up to request clarification or add additional context in comments.

1 Comment

This works! Sorry I forgot to accept this as answer earlier.

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.