使用 XPath 和 VB.NET 解析包含命名空间的 XML [英] Using XPath and VB.NET to parse XML containing namespsaces

查看:24
本文介绍了使用 XPath 和 VB.NET 解析包含命名空间的 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有几个相关的问题,但没有一个能提供我需要的指导.

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

假设以下 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

获取标题"的正确 XPath 语法是什么?

What is the correct XPath syntax to get the "title"?

为什么这是一个与类似主题的其他问题不同的问题的原因:

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

  1. 大多数其他示例都是 C#,我正在寻找 VB.NET解决方案.
  2. 其他示例未解决以下情况从先前选择的节点导航到一个节点.

我不是在寻找去除命名空间的解决方案;我想了解他们.谢谢.

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

推荐答案

你的内部 XPath,/rss:title,有一个前导 / 表示这个搜索应该无论您当前是否在子节点上,都从文档顶部开始.

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.

只需使用 rss:title 即可获得所需的节点.

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

这篇关于使用 XPath 和 VB.NET 解析包含命名空间的 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆