joebohen
joebohen

Reputation: 143

Parse a simple xml string

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?

Upvotes: 1

Views: 1431

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

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();

Upvotes: 1

noscreenname
noscreenname

Reputation: 3370

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.

Upvotes: 2

Related Questions