【问题标题】:retrieving nodes in xml with namespaces in .net使用 .net 中的命名空间检索 xml 中的节点
【发布时间】:2023-03-31 12:10:01
【问题描述】:

我来自 vb6 背景。 .net 新手和 xml 新手。我正在尝试从 xml 文件中检索节点。我发现了几种使用的方法(xmltextreader/serialization、xmldocument、xpath)我使用 xpath 只是因为我首先得到了一些结果:) 我的问题我确定与命名空间相关,但我发现的所有示例都比简单得多我有的xml。这是我需要访问的部分 xml 和我的代码的 sn-p。

<?xml version="1.0" encoding="utf-8"?>
<MTConnectStreams xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:mtconnect.org:MTConnectStreams:1.2 http://mtconnect.org/schemas/MTConnectStreams_1.2.xsd" xmlns="urn:mtconnect.org:MTConnectStreams:1.2">
  <Header creationTime="2012-11-29T12:30:19Z" instanceId="2" nextSequence="1918272" sender="Tarus MTConnect Instance" bufferSize="5000" firstSequence="1913272" lastSequence="1918271" version="1.2" />
  <Streams>
    <DeviceStream name="Vertical Bridge" uuid="TPIVB1">
      <ComponentStream component="Device" name="Vert" componentId="TPIVert">
        <Events>
          <Availability dataItemId="avail" timestamp="2012-11-27T23:19:40Z" sequence="44">AVAILABLE</Availability>
        </Events>
      </ComponentStream>
      <ComponentStream component="Linear" name="X" componentId="X">
        <Samples>
          <AxisFeedrate dataItemId="xs1" timestamp="2012-11-29T12:29:54Z" sequence="1717806" name="x_feed_cmd" subType="COMMANDED" units="MILLIMETER/SECOND">0</AxisFeedrate>

试图检索 AxisFeedrate 我有这个:

Dim xDoc As XPathDocument = New XPathDocument(sUrl)
Dim xNav As XPathNavigator = xDoc.CreateNavigator
Dim xIt As XPathNodeIterator = xNav.Select("//AxisFeedrate")
Dim i As Integer

For i = 1 To xIt.Count
    xIt.MoveNext()
    msgbox (xIt.Current.Value)

如果我将根节点更改为简单的“MTConnectStreams”,一切正常。在在线命名空间示例之后,我对我的代码进行了以下更改。但是在恢复原始根节点时,我仍然得到零结果。

Dim nsMgr = New XmlNamespaceManager(xNav.NameTable)
nsMgr.AddNamespace("ns", "http://www.w3.org/2001/XMLSchema-instance")
Dim xIt As XPathNodeIterator = xNav.Select("//ns:AxisFeedrate", nsMgr)

有人可以帮我克服这个障碍吗?

【问题讨论】:

    标签: .net vb.net xpath


    【解决方案1】:

    您的根节点声明默认命名空间是“urn:mtconnect.org:MTConnectStreams:1.2”,因此您需要使用它:

    Dim nsMgr = New XmlNamespaceManager(xNav.NameTable)
    nsMgr.AddNamespace("mt", "urn:mtconnect.org:MTConnectStreams:1.2")
    Dim xIt As XPathNodeIterator = xNav.Select("//mt:AxisFeedrate", nsMgr)
    

    【讨论】:

    • 谢谢。这么晚才回复很抱歉。我要么没有收到您的回复通知,要么是垃圾邮件过滤器吃掉了它。这行得通。所以 xmlns = 默认命名空间和 xmlns:xsi (或 :whatever)是额外的命名空间。
    • 不用担心,是的,这是正确的。在 XML 中,您可以使用默认名称空间在某个名称空间中包含元素而不使用前缀,但在 XPath 中,没有前缀始终意味着没有名称空间,因此要访问某个名称空间中的元素,您的 XPath 必须使用前缀,即使 XML本身没有。
    猜你喜欢
    • 2020-03-18
    • 2023-03-08
    • 1970-01-01
    • 2014-03-16
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    相关资源
    最近更新 更多