0

When running this code in Eclipse I get only null values:

    String recordsAsXML = "<vGVC:Row xmlns:vGVC=\"urn:com.versai:Bacon:GetViewContentsResponse.v1.0\"><vGVC:Column><vGVC:Value>aaa0</vGVC:Value><vGVC:ObjectName>2ff31656-b10c-11e0-99f6-e01321378d2a</vGVC:ObjectName></vGVC:Column><vGVC:ModifiedAfterQuery>false</vGVC:ModifiedAfterQuery></vGVC:Row>";


    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(recordsAsXML));

    Document doc = builder.parse(is);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//vGVC:Value/text()");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue()); 
    }

I'm trying to extract the "aaa0" value. Could you please help me understand what I'm doing wrong?

Thanks in advance, Michal.

1
  • 1
    You did not register the vGVC namespace with your XPath query. Commented Sep 29, 2011 at 12:59

1 Answer 1

2

You should use namespace context to let XPath know about your namespace, for example like this:

xpath.setNamespaceContext(new NamespaceContext() {  
    @Override public Iterator<?> getPrefixes(String namespaceURI) { return null; }
    @Override public String getPrefix(String namespaceURI) { return "vGVC"; }
    @Override public String getNamespaceURI(String prefix) { return "urn:com.versai:Bacon:GetViewContentsResponse.v1.0"; }
});

This should be done before calling evaluate, and if you have more than one namespace to handle, you can add them all in one implementation and use if statements to return the right prefix/URI.

More details in the javadocs here: http://download.oracle.com/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.