1

I have seen a few questions in this general area, but cannot find anything specific to Java and pulling a single node value.

I have a Web Service that returns values formatted like so:

<string xmlns="http://tempuri.org/">Hello</string>

In the Android application, I am trying to retrieve the 'Hello' part in the middle without the XML tags.

I have currently a method like so to do this:

public static String getParsedString(String xml)
{
    try
    {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource input = new InputSource();
        StringReader stringReader = new StringReader(xml);
        input.setCharacterStream(stringReader);

        Document document = documentBuilder.parse(input);

        NodeList nodes = document.getElementsByTagName("string");
        return nodes.item(0).getNodeValue().toString();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }

    return null;
}

However the node being parsed apparently contains no data, as when trying the toString() method, it throws the following error.

java.lang.NullPointerException

I'm not sure I need to account for the xmlns="http://tempuri.org/" in the document parser, but I can't figure it out.

1
  • First try for the xml root element and then look for particular element Commented Feb 15, 2017 at 12:16

1 Answer 1

2

Change the line

return nodes.item(0).getNodeValue().toString();

to

return nodes.item(0).getTextContent();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.