Java converts strings to XML and parses nodes
•
Java
See the English answer > how to parse a string containing XML in Java and retrieve the value of the root node? 6
Do I need to parse this string and get the text in the error message?
My string looks like this:
<response> <returnCode>-2</returnCode> <error> <errorCode>100</errorCode> <errorMessage>ERROR HERE!!!</errorMessage> </error> </response>
Is it better to parse a string or convert it to XML and then parse it?
Solution
I use Java's XML document library It's a bit messy, but it works
String xml = "<response>\n" + "<returnCode>-2</returnCode>\n" + "<error>\n" + "<errorCode>100</errorCode>\n" + "<errorMessage>ERROR HERE!!!</errorMessage>\n" + "</error>\n" + "</response>"; Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new InputSource(new StringReader(xml))); NodeList errNodes = doc.getElementsByTagName("error"); if (errNodes.getLength() > 0) { Element err = (Element)errNodes.item(0); System.out.println(err.getElementsByTagName("errorMessage") .item(0) .getTextContent()); } else { // success }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码