Get attribute values from matching XML nodes using XPath query

与世无争的帅哥 提交于 2019-12-03 11:47:46

For the following xml:

<root>
  <elem att='the value' />
</root>

You can get the "the value" text with this C# code

    XmlDocument xdoc = new XmlDocument();
    xdoc.LoadXml(text);
    Console.WriteLine(xdoc.SelectSingleNode("/root/elem/@att").Value);

If you're using .net 3.5 or later you could use linq to Xml

For a given xml document

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <storedProcedures>
    <storedProcedure name="usp_GET_HOME_PAGE_DATA">
      <resultSet name="Features"/>
      <resultSet name="Highlights"/>
    </storedProcedure>
    <storedProcedure name="usp_GET_FEATURES" />
    <storedProcedure name="usp_GET_FEATURE" />
    <storedProcedure name="usp_UPDATE_FEATURE" />
    <storedProcedure name="usp_GET_FEATURE_FOR_DISPLAY">
      <resultSet name="CurrentFeature"/>
      <resultSet name="OtherFeatures"/>
    </storedProcedure>
    <storedProcedure name="usp_GET_HIGHLIGHT_TITLES">
      <resultSet name="Highlights"/>
    </storedProcedure>
  </storedProcedures>
</root>

The following linq expression will get you the values of the "name" attributes of all storedProcedure node

XDocument xDcoument = XDocument.Load(xmlStoredProcSchemeFile);

  var storedProcedureNames = from doc in xDcoument.Descendants("storedProcedure")
                             select doc.Attribute("name").Value;

you could also use regular XPath syntax. In the code below the variable node holds the node identified by the "usp_GET_HOME_PAGE_DATA" name and then the attributes variable holds all child nodes (the attributes) of the selected node and it's children.

  XmlDocument xmlDocument = new XmlDocument();
  xmlDocument.Load(@"C:\inetpub\wwwroot\ASPNETBuilder\BusinessLayer\DataAccessCodeGenerationSchema.xml");
  var node = xmlDocument.DocumentElement.SelectSingleNode("./storedProcedures/storedProcedure[@name='usp_GET_HOME_PAGE_DATA']");
  var attributes = node.SelectNodes("./resultSet/@name");

solution to the initial problem of the exception being thrown...

var doc = new XPathDocument(new XmlNodeReader(xml));

should be replaced by...

var doc = new XmlDocument();
doc.load(*you can either specify the path to the file, the string out of which the xml document is to be generated or specify an xmlreader, look for more overloads*);

This will not throw the exception and the code will work just fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!