使用XPath解析XML源(元素节点属性)中的信息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用XPath解析XML源(元素节点属性)中的信息相关的知识,希望对你有一定的参考价值。

The code is run in [LINQPad](http://www.google.com/url?sa=t&source=web&ct=res&cd=1&ved=0CAsQFjAA&url=http%3A%2F%2Fwww.linqpad.net%2F&ei=exUgS-a-KZOotgOs39T9CQ&usg=AFQjCNFw-ZpPkP4je7u9udiur5Wg5us7tQ&sig2=gA-_2y2xnTKzK2A9CVxXfg), 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:





testfpga


test





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:UserspatkDesktopfile.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. }

以上是关于使用XPath解析XML源(元素节点属性)中的信息的主要内容,如果未能解决你的问题,请参考以下文章

Python解析库lxml与xpath用法总结

XPath注入

xpath语法

xPath 用法总结整理

XPath

Python爬虫--Xpath