Search code examples
xml-parsingtcltdom

Unable to parse XML with multiple namespaces using tcl and tdom


I am trying to parse a XML using tcl and tdom package. I am having trouble doing this as the node I want to parse is a child to a node with multiple namespaces. How would I be able to parse the realmCode or title element? Below is what I have tried:

package require tdom

set XML {<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="http://www.cerner.com/cda_stylesheet/" ?>
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sdtc="urn:hl7-org:sdtc" xsi:schemaLocation="urn:hl7-org:v3 ../../../CDA%20R2/cda-schemas-and-samples/infrastructure/cda/CDA.xsd" classCode="DOCCLIN" moodCode="EVN">
    <realmCode code="US" />
    <title>Discharge Summary</title>
</ClinicalDocument>}

set nsmap {
  a urn:hl7-org:v3
  x http://www.w3.org/2001/XMLSchema-instance
  s urn:hl7-org:sdtc
}

set doc [dom parse $XML]
set root [$doc documentElement]
set node [$root selectNodes -namespaces $nsmap "/a:ClinicalDocument/title"]
#set node [$root selectNodes "/ClinicalDocument/title"] ;# tried this as well - does not work

$doc delete

Solution

  • You need to specify the namespace for every level of the path, not just the root. Use

    set title [$root selectNodes -namespaces $nsmap /a:ClinicalDocument/a:title]
    set realm [$root selectNodes -namespaces $nsmap /a:ClinicalDocument/a:realmCode/@code]
    

    etc.