【问题标题】:Not reading XML elements with namespace不使用命名空间读取 XML 元素
【发布时间】:2013-09-16 15:03:29
【问题描述】:

我有以下 XML 文档信息:

<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:hl7-org:v3 CDA_SDTC.xsd" xmlns="urn:hl7-org:v3" xmlns:cda="urn:hl7-org:v3" xmlns:sdtc="urn:hl7-org:sdtc">
  <component>
    <structuredBody>
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.22.2.45" />
          <title>Instructions</title>
          <text>
            <paragraph>Putting instructions into the node to read out into the text area.</paragraph>
          </text>
        </section>
      </component>
    </structuredBody>
  </component>
</Document>

我必须让 VB.NET 页面加载 XML 文档才能查找此特定信息并将段落节点的内容放入网页上的文本区域表单字段中。这没有问题,但是文档根目录添加了一些命名空间信息,现在它无法正常工作。这是 VB.NET 代码:

m_nodelist = m_xmld.SelectNodes("Document/component/structuredBody/component/section")
For Each m_node In m_nodelist
  If m_node("title").InnerText = "Instructions" Then
    Dim Instructions As String = m_xmld.SelectSingleNode("Document/component/structuredBody/component/section[title='Instructions']/text/paragraph").InnerText
    txtInstructions.Text = Replace(patientInstructions, "<br>", Chr(10) & Chr(13))
    hfInstructionsOld.Value = Replace(patientInstructions, "<br>", Chr(10) & Chr(13))
  End If
Next

我认为它以前可以工作,因为根节点没有定义命名空间。现在确实如此。我不知道如何更改 VB.NET 代码来解决这个问题。

【问题讨论】:

    标签: asp.net xml vb.net xml-namespaces xmldocument


    【解决方案1】:

    由于现在在根元素上定义了默认命名空间,因此默认情况下,所有元素都属于该命名空间。使用 XPath 时(就像使用 SelectNodesSelectSingleNodes 一样),您必须始终显式指定命名空间。使用 XPath 无法指定默认名称空间,当没有显式指定名称空间时始终使用该名称空间。操作方法如下:

    Dim nsmgr As New XmlNamespaceManager(m_xmld.NameTable)
    nsmgr.AddNamespace("x", "urn:hl7-org:v3")
    m_nodelist = m_xmld.SelectNodes("x:Document/x:component/x:structuredBody/x:component/x:section", nsmgr)
    For Each m_node In m_nodelist
        If m_node("title").InnerText = "Instructions" Then
            Dim Instructions As String = m_xmld.SelectSingleNode("x:Document/x:component/x:structuredBody/x:component/x:section[x:title='Instructions']/x:text/x:paragraph", nsmgr).InnerText
            txtInstructions.Text = Replace(patientInstructions, "<br>", Chr(10) & Chr(13))
            hfInstructionsOld.Value = Replace(patientInstructions, "<br>", Chr(10) & Chr(13))
        End If
    Next
    

    或者,如果您希望它只是从根元素动态获取命名空间,您可以这样做:

    nsmgr.AddNamespace("x", m_xmld.DocumentElement.NamespaceURI)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多