How to use jdom parse xml with namespace? #107

Closed
michelya opened this Issue Jan 8, 2013 · 1 comment

Projects

None yet

2 participants

@michelya
michelya commented Jan 8, 2013

xml is here

<?xml version="1.0" encoding="UTF-8"?>
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:mif="urn:hl7-org:v3/mif" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://wwww.wspt.guo/CDA.xsd">
    <realmCode code="CN"/>
    <typeId root="2.16.840.1.113883.1.3" extension="POCD_HD000040"/>
    <templateId root="SD.10.1" assigningAuthorityName="phservice" extension="DT20120006V1"/>

code is here

        Document doc = sax.build(file);
        XPathFactory xpfac = XPathFactory.instance()
        XPathExpression xp = xpfac.compile("/ClinicalDocument",   Filters.element(),null,Namespace.getNamespace("urn:hl7-org:v3"));
        List<Element> list=xp.evaluate(doc);

running will throw a error
The default (no prefix) Namespace URI for XPath queries is always '' and it cannot be redefined to 'urn:hl7-org:v3'.

but i try it

   Document doc = sax.build(file);
        XPathFactory xpfac = XPathFactory.instance()
        XPathExpression xp = xpfac.compile("/ClinicalDocument",   Filters.element(),null,Namespace.Namespace.NO_NAMESPACE);
        List<Element> list=xp.evaluate(doc);

it not find anything.

@rolfl
Collaborator
rolfl commented Jan 8, 2013

See the Javadoc: http://jdom.org/docs/apidocs/org/jdom2/xpath/XPathFactory.html#compile%28java.lang.String,%20org.jdom2.filter.Filter,%20java.util.Map,%20org.jdom2.Namespace...%29

This is based ont eh XPath spec here: http://www.w3.org/TR/xpath/#node-tests (see the paragraph on QNames).

XPath Expressions are always namespace aware (if the Element has a Namespace then the XPath must reference it by namespace). Also, in XPath expressions, the 'default' namespace is always in the URI "". Thus, the URI of the default namespace of the elkement may be different to the default URI of the XPath. In your case you need to do the following (choosing 'myns' as a convenient prefix):

XPathExpression xp = xpfac.compile("/myns:ClinicalDocument",   Filters.element(),null,Namespace.getNamespace("myns", "urn:hl7-org:v3"));
List<Element> list=xp.evaluate(doc);
@rolfl rolfl closed this Jan 8, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment