Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parse XML with XmlDocument

Status
Not open for further replies.
Oct 3, 2007
15
0
0
US
I have an xml file I'm trying to read that looks like this:

Code:
<?xml version="1.0" encoding="utf-8"?>
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:cda="urn:hl7-org:v3" xmlns:xsi="[URL unfurl="true"]http://www.w3.org/2001/XMLSchema-instance"[/URL] xsi:schemaLocation="urn:hl7-org:v3 [URL unfurl="true"]http://xreg2.nist.gov:8080/hitspValidation/schema/cdar2c32/infrastructure/cda/C32_CDA.xsd"[/URL] xmlns:sdtc="urn:hl7-org:sdtc">
  <recordTarget>
    <patientRole>
      <addr>
         <streetAddressLine>123 MAIN ST</streetAddressLine>
      </addr>		
      <addr>
         <streetAddressLine>987 NORTH ST</streetAddressLine>
      </addr>				
    </patientRole>
  </recordTarget>
</ClinicalDocument>

And I'm trying to read and output all the streetAddressLine. My code is

Code:
Dim xmlDoc As New XmlDocument()
Dim namespaces As New XmlNamespaceManager(xmlDoc.NameTable)
namespaces.AddNamespace("ns", "urn:hl7-org:v3")

xmlDoc.Load("C:\testXML.xml")

Dim nodes As XmlNodeList = xmlDoc.DocumentElement.SelectNodes("/ClinicalDocument/recordTarget/patientRole/addr", namespaces)
Dim addr As String = ""
For Each node As XmlNode In nodes
  addr = node.SelectSingleNode("streetAddressLine").InnerText
  MessageBox.Show(addr)
Next

It will not output the addressStreetLine. If I remove the xmlns="urn:hl7-org:v3" namespace it works fine. What do I need to do to get it to work with the namespace.

Thanks,
 
try the following
Code:
Dim xmlDoc As New XmlDocument()
Dim namespaces As New XmlNamespaceManager(xmlDoc.NameTable)
namespaces.AddNamespace("ns", "urn:hl7-org:v3")

xmlDoc.Load("C:\testXML.xml")

Dim nodes As XmlNodeList = xmlDoc.DocumentElement.SelectNodes("/[COLOR=#F57900]ns:[/color]ClinicalDocument/[COLOR=#F57900]ns:[/color]recordTarget/[COLOR=#F57900]ns:[/color]patientRole/[COLOR=#F57900]ns:[/color]addr", namespaces)
Dim addr As String = ""
For Each node As XmlNode In nodes
  addr = node.SelectSingleNode("[COLOR=#F57900]ns:[/color]streetAddressLine"[COLOR=#F57900], namespaces[/color]).InnerText
  MessageBox.Show(addr)
Next
 
Note that what you are asking isn't parsing XML at all, the XmlDocument is doing all of the parsing when you load it.

What you are asking about is spelunking the DOM, which can be done by iterating and descending the DOM tree or when (rarely) warranted the slower approach relying on XPath queries as given above.

You should be able to get and iterate the <addr/> node collection far more simply and directly.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top