3

i need to deserilize an XML file, which has a variable structure. Two example's:

<xml>
    <OrgUnit GUID="1111">
        <OrgUnit GUID="2222">
            <OrgUnit GUID="3333" />
            <OrgUnit GUID="4444" />
            ...
        </OrgUnit>
    </OrgUnit>
</xml>

<xml>
    <OrgUnit GUID="1111" />
    <OrgUnit GUID="2222" />
    <OrgUnit GUID="3333">
        <OrgUnit GUID="4444" />
        <OrgUnit GUID="5555" />
    </OrgUnit>
</xml>

...

As you can see, the element names are always the same. The problem is, that the nesting of the elements varys all the time. Is there any way to implement this with XmlSerializer?

0

2 Answers 2

3
public class xml
{
    [XmlElement("OrgUnit")]
    public OrgUnit[] OrgUnits { get; set; }
}

public class OrgUnit
{
    [XmlAttribute]
    public int GUID { get; set; }

    [XmlElement("OrgUnit")]
    public OrgUnit[] OrgUnits { get; set; }
}

and then:

class Program
{
    static void Main()
    {
        var serializer = new XmlSerializer(typeof(xml));
        using (var reader = XmlReader.Create("test.xml"))
        {
            var result = (xml)serializer.Deserialize(reader);
        }
    }
}

It will work with any nesting depths of OrgUnit.

Sign up to request clarification or add additional context in comments.

Comments

0

When using xml documents as the starting point I always prefer an xsd as the contract between the file and the parsing code. Note that I have used 'OrgUnits' as the root node.

You can use xsd.exe to create serializable classes for you.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="OrgUnits">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="OrgUnit"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="OrgUnit">
    <xs:complexType mixed="true">
      <xs:sequence>
        <xs:element minOccurs="0" maxOccurs="unbounded" ref="OrgUnit"/>
      </xs:sequence>
      <xs:attribute name="GUID" use="required" type="xs:integer"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

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.