Wednesday, January 30, 2013

Parse XML file with Linq, part 2: Adding namespaces

Let's read plugin information from the following XML file.

The difference with previous example is that XML namespace is now in use:

<Configuration xmlns="">
    <UserSetting Name="UsePlugins" Value="True" />
    <Plugin Name="BackgroundWorker" />
    <Plugin Name="UserInteraction" />
Plugin information is read into list of the following class:

public class Plugin
    public String Name { get; set; }
And the required code is (changes in red color):

namespace LinqTest
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    static public class ParseXml
        static public List<Plugin> Example2(String fileName)
            XDocument document = XDocument.Load(fileName);
            XNamespace ns = document.Root.Name.Namespace;
            List<Plugin> plugins = new List<Plugin>(from plugin in document.Descendants(ns + "Plugin")
                                                    select new Plugin
                                                        Name = (String)plugin.Attribute("Name")
            return plugins;

All blog entries related to "Parse XML file with Linq":

No comments:

Post a Comment