Java convert string to xml and parsing node

Hello, I am returning a string from a web service.

Do I need to parse this line and get the text in the error message?

My line looks like this:

<response> <returnCode>-2</returnCode> <error> <errorCode>100</errorCode> <errorMessage>ERROR HERE!!!</errorMessage> </error> </response> 

Is it better to just parse a string or convert to xml and then parse?

+6
source share
3 answers

I would use Java XML document libraries. This is a bit of a mess, 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 } 
+13
source

I would probably use an XML parser to convert it to XML using the DOM, and then get the text. The advantage of this is to be reliable and deal with any unusual situations, such as a line like this, where something has been commented on:

 <!-- commented out <errorMessage>ERROR HERE!!!</errorMessage> --> 

If you try to make it out yourself, then you may be mistaken in such things. In addition, it has the advantage that if the requirements are expanded, then it is very easy to change your code.

http://docs.oracle.com/cd/B28359_01/appdev.111/b28394/adx_j_parser.htm

+2
source

This is an XML document. Use an XML parser.

You can split it using string operations. But you need to worry about decoding objects, character encoding, CDATA sections, etc. The XML parser will do all this for you.

Abandon the JDOM for a simpler approach to parsing XML than using the original DOM / SAX implementations.

+1
source

Source: https://habr.com/ru/post/956949/


All Articles