Wednesday, January 30, 2013

Parse XML file with Linq, part 3: Complex structures

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

The difference with previous example is that XML now has complex structure:

<Configuration xmlns="http://schemas.vurdalakov.net/linqtest">
  <UserSettings>
    <UserSetting Name="UsePlugins" Value="True" />
  </UserSettings>
  <Plugins>
    <Plugin Name="BackgroundWorker" Type="Background">
      <Runtime>
        <Implementation EntryPoint="BackgroundPlugin.Run" />
      </Runtime>
      <Files>
        <File Name="BackgroundPlugin.dll"/>
        <File Name="BackgroundPlugin.cfg"/>
      </Files>
    </Plugin>
    <Plugin Name="UserInteraction" Type="UI">
      <Runtime>
        <Implementation EntryPoint="UIPlugin.Execute" />
        <Files>
          <File Name="UIPlugin.dll"/>
          <File Name="UIPlugin.ini"/>
        </Files>
      </Runtime>
    </Plugin>
  </Plugins>
</Configuration>
Plugin information is read into the following class structure:

public class Plugin
{
    public String Name { get; set; }
    public String Type { get; set; }
    public PluginImplementation Implementation { get; set; }
    public List<PluginFile> Files { get; set; }
}

public class PluginImplementation
{
    public String EntryPoint { get; set; }
}

public class PluginFile
{
    public String Name { get; set; }
}
And the required code is:

static public List<Plugin> Example3(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"),
            Type = (String)plugin.Attribute("Type"),
            Implementation = new PluginImplementation()
            {
                EntryPoint = (String)plugin.Element(ns + "Runtime").Element(ns + "Implementation").Attribute("EntryPoint")
            },
            Files = new List<PluginFile>(from implementation in plugin.Descendants(ns + "File")
                select new PluginFile
                {
                    Name = (String)implementation.Attribute("Name")
                })
        });
    return plugins;
}


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

No comments:

Post a Comment