styleguide
styleguide

Reputation: 21

XPath issue using JDOM / Jaxen

In my program I am downloading a xml file, shown below.

The task should be very simple to extract just all the Attributes currency and rate.

I am using JDOM and have started as follows:

try {
    // TODO code application logic here
    SAXBuilder builder = new SAXBuilder();
    org.jdom.Document doc = builder.build("test.xml");
    List<?> all = XPath.selectNodes(doc, "/Envelope/Cube/Cube/@currency");
    for(Object o : all) {
        Attribute att = (Attribute) o;
        System.out.println("ausgbabe: " + att);
    }
}

Have tested several paths to get the entries but it is not working.

<?xml version="1.0" encoding="UTF-8"?> 
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> 
    <gesmes:subject>Reference rates</gesmes:subject> 
    <gesmes:Sender> 
        <gesmes:name>European Central Bank</gesmes:name> 
    </gesmes:Sender> 
    <Cube> 
        <Cube time='2012-01-17'> 
            <Cube currency='USD' rate='1.2790'/> 
            <Cube currency='JPY' rate='98.20'/> 
            <Cube currency='BGN' rate='1.9558'/> 
            <Cube currency='CZK' rate='25.650'/> 
            <Cube currency='DKK' rate='7.4353'/> 
            <Cube currency='GBP' rate='0.83045'/> 
        </Cube> 
    </Cube> 
</gesmes:Envelope>

Upvotes: 2

Views: 1891

Answers (2)

javanna
javanna

Reputation: 60245

You need to bound namespaces to your xpath object. You should create the xpath object like this (I had to add a new Cube entry to your xpath):

XPath xpath = XPath.newInstance("/gesmes:Envelope/root:Cube/root:Cube/root:Cube/@currency");

then add your namespace declarations to it:

xpath.addNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");
xpath.addNamespace("root", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");

In fact, the Envelope element has the "http://www.gesmes.org/xml/2002-08-01" namespace uri, while all the Cube elements have the "http://www.ecb.int/vocabulary/2002-08-01/eurofxref" namespace uri, declared as default namespace. You can use the namespace prefix you want in your xpath, but the uri must match.
Then search through the document like this using the xpath you created:

List<?> all = xpath.selectNodes(doc);

I tested this code with your xml and it produces the following output:

ausgbabe: [Attribute: currency="USD"]
ausgbabe: [Attribute: currency="JPY"]
ausgbabe: [Attribute: currency="BGN"]
ausgbabe: [Attribute: currency="CZK"]
ausgbabe: [Attribute: currency="DKK"]
ausgbabe: [Attribute: currency="GBP"]

Upvotes: 6

OrangeDog
OrangeDog

Reputation: 38807

You have namespaces in your xml that you haven't told the XPath engine about. You need to use a javax.xml.namespace.NamespaceContext. See this article for a full explanation and guide to get it working.

Upvotes: 1

Related Questions