views:

45

answers:

0

Hi Iam trying to process an XML file with a namespace using JAXP/XPATH - but there is no output - any help would be great. I'm struggling with the namespace syntax...

Basically I would like to process the currency and rates below in the XML file.

XML FILE

<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"&gt;
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
    <gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
    <Cube time='2010-07-19'>
        <Cube currency='USD' rate='1.2957'/>
        <Cube currency='JPY' rate='112.84'/>
        <Cube currency='BGN' rate='1.9558'/>
        <Cube currency='CZK' rate='25.429'/>
        <Cube currency='DKK' rate='7.4529'/>
    </Cube>
</Cube>

Java Parsing Class

public class XPathExampleDOM {

public static void main(String[] args) {
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);

        DocumentBuilder builder = domFactory.newDocumentBuilder();

        Document document = builder.parse(new InputSource("file:src\\com\\taichou\\XPath\\ECBFXRates.xml"));

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        xpath.setNamespaceContext(new NamespaceContext() {
            public String getNamespaceURI(String prefix) {
                if (prefix.equals("gesmes")) {
                    return "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";
                }

                return "";
            }

            public String getPrefix(String namespaceURI) {
                if (namespaceURI.equals("http://www.ecb.int/vocabulary/2002-08-01/eurofxref")) {
                    return "gesmes";
                }

                return "";
            }

            public Iterator getPrefixes(String namespaceURI) {
                List<String> list = new ArrayList<String>();

                if (namespaceURI.equals("http://www.ecb.int/vocabulary/2002-08-01/eurofxref")) {
                    list.add("gesmes");
                }

                return list.iterator();
            }
        });

        Object nodes = xpath.evaluate("//gesmes:/Cube", document.getDocumentElement(), XPathConstants.NODESET);

        if (nodes instanceof NodeList) {
            for (int i = 0; i < ((NodeList)nodes).getLength(); i++) {
                System.out.println(((NodeList)nodes).item( i).getTextContent());
            }
        }