2013-09-16 250 views
1

不讀取XML元素我有下面的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

由於現在在根元素上定義了默認命名空間,因此默認情況下所有元素都屬於該命名空間。在使用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) 
+1

這工作。感謝您的信息和幫助。 – jjasper0729