Posted By

pckujawa on 12/09/09


Tagged

xml XPath


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

vali29
khouser
tonicglop
icecreamboyy


Parsing information from an XML source (elements, nodes, attributes) using XPath


 / Published in: C#
 

URL: http://www.aspfree.com/index2.php?option=content&task=view&id=2426&pop=1&hide_ads=1&page=0&hide_js=1

The code is run in LINQPad, which is where the Dump extension method comes from. You can pretend that it just outputs ToString. The input file for this snippet looks like so:

<configuration>
  <userSettings>
    <HawkConfigGUI.Properties.Settings>
      <setting>
        <value>testfpga</value>
      </setting>
      <setting>
        <value>test</value>
      </setting>
    </HawkConfigGUI.Properties.Settings>
  </userSettings>
</configuration>

The output of the snippet is

FpgaFilePath => testfpga
FirmwareFilePath => test

So the snippet pulls out an attribute from the 'setting' element and the content (text between tags) of the 'value' sub-element.

  1. var path = @"C:\Users\patk\Desktop\file.xml";
  2. var doc = XDocument.Load(path);
  3. //doc.DescendantNodes().Dump();
  4. //doc.XPathSelectElements("//setting").Dump();
  5. //doc.XPathSelectElements("//setting").Attributes().Dump();
  6. //doc.XPathSelectElements("//setting").Descendants().Dump();
  7. var settings = doc.XPathSelectElements("//setting");
  8. foreach (var setting in settings){
  9. var name = setting.Attribute("name").Value;
  10. // setting.DescendantNodes().Dump();
  11. var value = setting.XPathSelectElements("value").Single().FirstNode;
  12. (name + " => " + value).Dump();
  13. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: pckujawa on December 9, 2009

XPathSelectElements is in System.Xml.XPath

You need to login to post a comment.