C# XML Parsing Extracting Values and using XML to Linq with XDocument

On my blog the most accessed articles are the basic ones on XML which has suprised me. So In this article I will focus on the new kid on the block the Linq derived XDocument. In the following example I will load the Xml then enumerate over the child nodes, to extract specific values and then display them.

I am loading the xml directly, but you can load it from other locations using the Load option of XDocument.

string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<widgets>
    <widget>
        <url>~/Portal/Widgets/ServicesList.ascx</url>
        <castAs>ServicesWidget</castAs>
        <urlType>ascx</urlType>
        <parameters>
            <PortalCategoryId>3</PortalCategoryId>
        </parameters>
    </widget>
    <widget>
        <url>www.omegacoder.com</url>
        <castAs>ServicesWidget</castAs>
        <urlType>htm</urlType>
        <parameters>
            <PortalCategoryId>41</PortalCategoryId>
        </parameters>
    </widget>
</widgets>";

XDocument loaded = XDocument.Parse( xml );

var widgets = from x in loaded.Descendants( "widget" )
              select new
              {
                  URL = x.Descendants( "url" ).First().Value,
                  Category = x.Descendants( "PortalCategoryId" ).First().Value
              };

foreach ( var wd in widgets )
    Console.WriteLine( "Widget at ({0}) has a category of {1}", wd.URL, wd.Category );

/* Outputs:

Widget at (~/Portal/Widgets/ServicesList.ascx) has a category of 3
Widget at (www.omegacoder.com) has a category of 41

*/
Share

9 Comments

  1. Bob says:

    What imports are required for Xdocument? Can’t find any references on it, and XML/XML.Xpath, Linq aren’t cutting it.

  2. Terry says:

    using System.Xml.Linq;

  3. Dpool says:

    In this “Select” setup, Is there a way to assign a value to ‘Category’ if there is no “PortalCategoryID” value for a particular ‘widget’ in the XML file?

  4. omegaman says:

    Use the null coalescing operator and provide a default value, also make don’t use first but FirstOrDefault. Change the above to this:

    Category = (string)x.Descendants( “PortalCategoryId” ).FirstOrDefault() ?? “No Value”

    HTH

  5. Alex says:

    Thank you for this post; it was of great help. I am somewhat new to using Linq and parsing XML documents.

  6. Mari says:

    Hi,

    You mentioned that there are other load options for xdocument. Would you be able to give some examples?
    You are defining the Xml string directly, what if I wanted to parse out the xml from a file that was part of my project?

    I’m basically trying to define the position (format in a proper tree) of my nodes based on their parent_id and id in my xml file.
    It looks something like this:

    Mary Jones

    Lisa Lee

    Chris Clown

    Susan Bee

    For example Lisa lee should be under Mary Jones and Susan Bee should be under Lisa Lee.

    Thank you for your help!

  7. Mari says:

    Please disregard the previous post. The tags are missing.

    item parent_id=’0′ id=’1′
    content
    name
    Mary Jones
    /name
    /content
    /item

    item parent_id=’1′ id=’2′
    content
    name
    Lisa Lee
    /name
    /content
    /item

    item parent_id=’1′ id=’7′
    content
    name
    Chris Clown
    /name
    /content
    /item

    item parent_id=’2′ id=’3′
    content
    name
    Susan Bee
    /name
    /content
    /item

  8. Mari says:

    Hi OmegaMan,

    Thank you for the link!

Leave a Reply