使用XPath解析XML文档

编程入门 行业动态 更新时间:2024-10-15 10:17:30
本文介绍了使用XPath解析XML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让我们说我有以下xml(简单示例)

Lets say I have the following xml (a quick example)

<rows> <row> <name>one</name> </row> <row> <name>two</name> </row> </rows>

我试图通过使用XmlDocument和XPath来解析它(最终,我可以列出行).

I am trying to parse this by using XmlDocument and XPath (ultimately so I can make a list of rows).

例如...

XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); foreach(XmlNode row in doc.SelectNodes("//row")) { string rowName = row.SelectSingleNode("//name").InnerText; }

为什么在我的foreach循环中,rowName总是一个"?我希望它在第一次迭代中为一个",而在第二次迭代中为两个".

Why, within my foreach loop, is rowName always "one"? I am expecting it to be "one" on the first iteration and "two" on the second.

似乎//name获得了文档中的第一个实例,而不是我所期望的行中的第一个实例.毕竟,我要在行"节点上调用该方法.如果这只是它是如何工作的",那么任何人都可以解释一下如何更改它以满足我的需求吗?

It seems that //name gets the first instance in the document, rather than the first instance in the row as I would expect. After all, I am calling the method on the "row" node. If this is "just how it works" then can anybody please explain how I could change it to work to my needs?

谢谢

推荐答案

XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); foreach(XmlNode row in doc.SelectNodes("//row")) { var rowName = row.SelectSingleNode("name"); }

您发布的代码是否正确?我在row.SelectNode()上收到编译错误,因为它不是XmlNode的成员.

Is the code you posted actually correct? I get a compile error on row.SelectNode() as it isn't a member of XmlNode.

无论如何,上面的示例都可以,但是假定< row> 节点内仅一个< name> 节点,因此您可能需要使用如果不是这种情况,请使用SelectNodes()代替 SelectSingleNode().

Anyway, my example above works, but assumes only a single <name> node within the <row> node so you may need to use SelectNodes() instead of SelectSingleNode() if that is not the case.

如其他人所示,使用 .InnerText 来获取值.

As others have shown, use .InnerText to get just the value.

更多推荐

使用XPath解析XML文档

本文发布于:2023-11-28 16:13:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643081.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   XPath   XML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!