不读取带有命名空间的XML元素

时间:2013-09-16 15:03:30

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

我有以下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代码来解决这个问题。

1 个答案:

答案 0 :(得分: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)