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?

Matthieu
  • 2,736
  • 4
  • 57
  • 87
joebohen
  • 145
  • 1
  • 14

2 Answers2

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.

Community
  • 1
  • 1
noscreenname
  • 3,314
  • 22
  • 30
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();
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 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!) – Matthieu Jul 19 '16 at 13:22
  • 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. – joebohen Jul 19 '16 at 13:33
  • 1
    @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()` – Joop Eggen Jul 19 '16 at 14:15