Friendly way to parse XDocument

Posted by Oli on Stack Overflow See other posts from Stack Overflow or by Oli
Published on 2012-11-16T04:18:12Z Indexed on 2012/11/16 5:00 UTC
Read the original article Hit count: 151

Filed under:
|
|
|
|

I have a class that various different XML schemes are created from. I create the various dynamic XDocuments via one (Very long) statement using conditional operators for optional elements and attributes.

I now need to convert the XDocuments back to the class but as they are coming from different schemes many elements and sub elements may be optional. The only way I know of doing this is to use a lot of if statements.

This approach doesn't seem very LINQ and uses a great deal more code than when I create the XDocument so I wondered if there is a better way to do this?

An example would be to get

<?xml version="1.0"?>
<root xmlns="somenamespace">
    <object attribute1="This is Optional" attribute2="This is required">
        <element1>Required</element1>
        <element1>Optional</element1>
        <List1>
            Optional List Of Elements
        </List1>
        <List2>
            Required List Of Elements
        </List2>
    </object>
</root>

Into

public class Object()
{
    public string Attribute1;
    public string Attribute2;
    public string Element1;
    public string Element2;
    public List<ListItem1> List1;
    public List<ListItem2> List2;
}

In a more LINQ friendly way than this:

public bool ParseXDocument(string xml)
{
    XNamespace xn = "somenamespace";            
    XDocument document = XDocument.Parse(xml);

    XElement elementRoot = description.Element(xn + "root");
    if (elementRoot != null)
    {
        //Get Object Element
        XElement elementObject = elementRoot.Element(xn + "object");
        if(elementObject != null)
        {
            if(elementObject.Attribute(xn + "attribute1") != null)
            {
                Attribute1 = elementObject.Attribute(xn + "attribute1");
            }
            if(elementObject.Attribute(xn + "attribute2") != null)
            {
                Attribute2 = elementObject.Attribute(xn + "attribute2");
            }
            else
            {
                //This is a required Attribute so return false
                return false;
            }
            //If, If/Elses get deeper and deeper for the next elements and lists etc.... 
        }
        else
        {
            //Object is a required element so return false
            return false;
        }
    }
    else
    {
        //Root is a required element so return false
        return false;
    }
    return true;
}

Update: Just to clarify the ParseXDocument method is inside the "Object" class. Every time an xml document is received the Object class instance has some or all of it's values updated.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET