简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM