Current location - Quotes Website - Signature design - How to extract STATE and ERRORCODE values from the following xml string?
How to extract STATE and ERRORCODE values from the following xml string?
First, let's talk about your xml problem:

1. Your P tag is not closed, so I'll close it for you.

2. I will use dom4j to parse, add dependencies for the project or download jar packages online by myself:

& lt dependency & gt

& ltgroupId & gtdom4j & lt/groupId & gt;

& ltartifactId & gtdom4j & lt/artifact id & gt;

& lt version & gt1.6.1< /version & gt;

& lt/dependency & gt;

3. The target value you want to get is in the attribute of the last S tag. When dom4j is used for parsing, dom4j needs that ""symbol, otherwise it will report an error: org.dom4j.documentexception: Error in line 5 of the document? : The attribute value of' ca_out' associated with element type' s' cannot contain'.

& lt? Xml version =" 1.0 "encoding ="UTF-8"? & gt

& ltp & gt

& lts err flag = " 0 "/& gt;

& lts errtext = " "/& gt;

& lts ca _ out = " & amplt; State and society. gt; 0 & amplt; /STATE & amp; gt; & amplt; Error code > 0 & amplt; /error code > ”/& gt;

& lt/p & gt;

4. After parsing the attribute of ca_out, the attribute value is

& ltroot & gt

& ltSTATE & gt0 & lt/STATE & gt;

& lt error code & gt0</errorcode >

& lt/root & gt;

So we can parse it.

5. The code is as follows:

Common class test {

The public static void main(String[] args) throws an exception {

String xml = " & lt? Xml version =\" 1.0\ "encoding =\"UTF-8\"? & gt\n" +

“& ltp & gt\n" +

“& lts err flag = \ " 0 \ "/& gt; \n" +

“& lts errtext=\"\"/>\n" +

“& lts ca _ out = \ " & amplt; State and society. gt; 0 & amplt; /STATE & amp; gt; & amplt; Error code > 0 & amplt; /error code > \ "/>; \n" +

“& lt/p >; ;

SAXReader reader = new SAXReader();

document doc = reader . read(new bytearray inputstream(XML . getbytes(" UTF-8 "))); //Read the xml string

element root = doc . getrootelement();

List & lt element & gt elements = root.elements ();

For (element element: element) {

attribute attribute = element . attribute(" ca _ out "); //get the ca_out node attribute.

If (property! = null) {

string ca _ out value = attribute . getvalue();

System.out.println("ca_out in ca _ out: "+ca _ outvalue+"\ n ");

//The obtained ca_out is not xml and has no root node. Add a root node to it first and convert it into standard xml before processing.

String caOutXml = "< root >;" +ca _ out value+" & lt; /root >;

document caout doc = reader . read(new bytearrayiputstream(caout XML . getbytes(" UTF-8 ")));

element caOutRoot = caoutdoc . getrootelement();

List & lt element & gtcaoutelements = caoutroot.elements ();

for(Element caout Element:caout elements){

system . out . println(caout element . getname()+" = "+caout element . gettext());

}

}

}

}

}

6. Operation result: