使用 XPath 和 VB.NET 解析包含命名空间的 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16949495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using XPath and VB.NET to parse XML containing namespsaces
提问by DWRoelands
There are several related questions, but none which provide the guidance I need.
有几个相关的问题,但没有一个可以提供我需要的指导。
Assuming the following XML:
假设以下 XML:
<?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" >
<entry>
<title type="text">This is the title</title>
<content>lorem ipsum</content>
</entry>
<entry>
<title type="text">This is the second title</title>
<content>lorem ipsum 2</content>
</entry>
</feed>
If this document had no namespaces, I could write code like this:
如果这个文档没有命名空间,我可以写这样的代码:
Public Sub ShowXML(XmlText As String)
Dim doc As New XmlDocument
doc.LoadXml(XmlText)
For Each Entry As XmlNode In doc.SelectNodes("//entry")
Console.WriteLine(Entry.SelectSingleNode("title").InnerText)
Next
End Sub
Because of namespaces, this is not possible. This is my latest attempt:
由于命名空间,这是不可能的。这是我最近的尝试:
Public Sub ShowXML(XmlText As String)
Dim doc As New XmlDocument
doc.LoadXml(XmlText)
Dim nsmgr As New XmlNamespaceManager(doc.NameTable)
nsmgr.AddNamespace("rss", "http://www.w3.org/2005/Atom")
For Each Entry As XmlNode In doc.SelectNodes("//rss:entry")
Console.WriteLine(Entry.SelectSingleNode("/rss:title").InnerText)
Next
End Sub
What is the correct XPath syntax to get the "title"?
获取“标题”的正确 XPath 语法是什么?
Reasons why this is a separate question from other ones on similar topics:
这是一个与类似主题的其他问题不同的问题的原因:
- Most of the other examples are C#, and I am looking for a VB.NET solution.
- The other examples do not address the scenario of navigating to a node from a previously-selected node.
- 大多数其他示例都是 C#,我正在寻找 VB.NET 解决方案。
- 其他示例没有解决从先前选择的节点导航到节点的情况。
I am not looking for a solution that strips namespaces; I want to understand them. Thank you.
我不是在寻找去除命名空间的解决方案;我想了解他们。谢谢你。
回答by Dave Michener
Your inner XPath, /rss:title, has a leading /which indicates that this search should begin from the top of the document regardless of the fact that you are currently on a child node.
您的内部 XPath/rss:title有一个前导/,它表明无论您当前是否在子节点上,此搜索都应从文档顶部开始。
Instead just use rss:titleand you'll get the node you are after.
而只是使用rss:title,你会得到你所追求的节点。

![多线程和套接字/TCP [VB.NET]](/res/img/loading.gif)