Category Archives: LINQ

Parsing XML with LINQ

Here’s a quick example using LINQ to parse some  XML and get at the sweet, sweet attributes therein.

Here’s the XML I want to parse:

<?xml version="1.0" encoding="utf-8" ?>
<DeafultConfigurationSets>
  <PageLayouts>

    <PageLayout name="xyzzy">
      <Tabs>
        <Tab TabOrder="1" TabLabel="x" SharePointContentType="a" AdditionalConstraints="ac1"/>
        <Tab TabOrder="2" TabLabel="y" SharePointContentType="b" AdditionalConstraints="ac2"/>
      </Tabs>
    </PageLayout>

    <PageLayout name="xyzzy2">
      <Tabs>
        <Tab TabOrder="100" TabLabel="x" SharePointContentType="a" AdditionalConstraints="ac1"/>
        <Tab TabOrder="101" TabLabel="y" SharePointContentType="b" AdditionalConstraints="ac2"/>
        <Tab TabOrder="103" TabLabel="z" SharePointContentType="c" AdditionalConstraints="ac3"/>
      </Tabs>
    </PageLayout>

  </PageLayouts>
</DeafultConfigurationSets>

I want to build up some tabs at runtime by parsing the above.  My tabs depend upon a page layout.  If my page layout’s name is “xyzzy2” then I want to get tabs 100, 101 and 103 (the tabs in <PageLayout name=”xyzzy2”>).

Here’s the LINQ that does it:

var allTabs =
              from p in
                  XElement.Parse(theXmlToParse).
                 
Elements("PageLayouts").
                  Elements("PageLayout")
              where (p.Attribute("name").Value.Equals("xyzzy2"))
              from m in p.Elements("Tabs").Elements("Tab")
              select m;

          Results.Text = string.Empty;

          foreach (var aTab in allTabs)
          {
              Results.Text +=
                  "Tab Order: " + aTab.Attribute("TabOrder").Value + " |" +
                  "Tab Label: " + aTab.Attribute("TabLabel").Value + " | " +
                  "SharePointContentType: " + aTab.Attribute("SharePointContentType").Value + " | " +
                  "AdditionalConstraints: " + aTab.Attribute("AdditionalConstraints").Value + "\r";
          }

In the above, the variable “theXmlToParse” is a string variable, but you can use the load() method on a stream if you like.

“Results” is a label on a web form and when this code executes, it looks like this:

SNAGHTML11cd2e7c

I haven’t worked out how to sort the results yet, so I’ll leave that for a future blog post.

</end>

Subscribe to my blog.

Follow me on Twitter at http://www.twitter.com/pagalvin