1

I have a simple xml and want to retrieve the value held in the 'String' which is either True or False. There are lots of suggested methods which look very complex! What would be the best way to do this?

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">"True"</string>

I am able to read the xml into an xmlReader as below.

XMLReader xmlReader = SAXParserFactory.newInstance()
                        .newSAXParser().getXMLReader();           
InputSource source = new InputSource(new StringReader(response.toString()));
xmlReader.parse(source);

How would I now get the value out of the reader?

4
  • 1
    That is not XML, which is a text containing something like <x> ... </x>. Commented Jul 19, 2016 at 11:43
  • The xml is <?xml version="1.0" encoding="utf-8"?> <string xmlns="tempuri.org/">"True"</string> Commented Jul 19, 2016 at 12:48
  • If you really have XML (what you insert is not XML ;) ) you can try use xpath for example,,, Commented Jul 19, 2016 at 13:06
  • how specific is your choice of API, ex. sax, stax or dom ? Commented Jul 23, 2016 at 3:23

2 Answers 2

2

You will first need to define a Handler :

public class MyElementHandler extends DefaultHandler {
        private boolean isElementFound = false;
        private String value;

    public String getValue() {
        return value;
    }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) {
            if (qName.equals("elem")) {
                isElementFound = true;
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) {
            if (qName.equals("elem")) {
                isElementFound = false;
            }
        }

        @Override
        public void characters(char ch[], int start, int length) {
            if (isElementFound) {
                value = new String(ch).substring(start, start + length);
            }
        }
    }

Then, the you parse your xml as follows :

String xml = response.toString();
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
InputSource source = new InputSource(new StringReader(xml));
//-- create handlers
MyAttributeHandler handler = new MyAttributeHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse(source);
System.out.println("value = " + handler.getValue());

More general question about sax parsing.

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

Comments

1

Here one does not need XML. A two-liner:

String xmlContent = response.toString();
String value = xmlContent.replaceFirst("(?sm)^.*<string[^>]*>([^<]*)<.*$", "$1");

if (value == xmlContent) { // No replace
    throw new IllegalStateException("Not found");
}
boolean result = Boolean.valueOf(value.trim().toLowerCase());

With XML one could do:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputSource);
String xml = doc.getDocumentElement().getTextContent();

3 Comments

I have mixed feeling about "+1: an awesome regex to parse an XML element" and "-1: it specifically asks for XML parsing, the simple format being just an example". Still thinking... OK, +1 because you give an example for XML (and thanks for the regex!)
Bit confused but got there in the end thanks. The value returned is always in the same format only the content changes either true or false so your replacement suggestion will suffice.
@Matthieu the same sentiments on my side: elaborating on basic XML parsing what is horrible, substituting it with DOM building and then child getting. Or hack off the thorns of that spiky XML - regex? Maybe a better API is needed: Xml.read(inputSource).xpath("/string/text()").toString()

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.