Using XPath and VB.NET to parse XML containing namespsaces

狂风中的少年 提交于 2019-12-01 09:47:31

问题


There are several related questions, but none which provide the guidance I need.

Assuming the following 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"?

Reasons why this is a separate question from other ones on similar topics:

  1. Most of the other examples are C#, and I am looking for a VB.NET solution.
  2. The other examples do not address the scenario of navigating to a node from a previously-selected node.

I am not looking for a solution that strips namespaces; I want to understand them. Thank you.


回答1:


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.

Instead just use rss:title and you'll get the node you are after.



来源:https://stackoverflow.com/questions/16949495/using-xpath-and-vb-net-to-parse-xml-containing-namespsaces

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