Java parsing XML using dom4j

Source: Internet
Author: User
Tags cdata object object

Target: Parses the specified XML and returns the data under the specified node in the form of a key = value

Required jar Packages: Dom4j1.6.1.jar, Jaxen-1.1.jar

<?XML version= "1.0" encoding= "UTF-8"?><Soap-env:envelopexmlns:soap-env= "http://schemas.xmlsoap.org/soap/envelope/"Xmlns:soap-enc= "http://schemas.xmlsoap.org/soap/encoding/"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd= "Http://www.w3.org/2001/XMLSchema">    <Soap-env:body>        <M:mainxmlns:m= "http://webservice.xnhdbbx.org/">            <arg0>                <! [Cdata[<business> <functioncode>400105</functioncode>                        <d401_19>411102</d401_19> <t104_03>1</t104_03> <list> <item id= ' 1 ' > <I201_00>FDAC4FC4                        22f5e339e04000</i201_00> </item> </list>                        <remark1/> <remark2/> <remark3/>                <remark4/> <remark5/> </business> ]]>            </arg0>        </M:main>    </Soap-env:body></Soap-env:envelope>
View Code

As on the XML, my goal is to get the item under the node data. Format is: i201_00=fdac4fc422f5e339e04000

Here is the code

 PackageCn.code;ImportJava.io.File;ImportJava.util.Iterator;Importjava.util.List;Importorg.dom4j.Document;Importorg.dom4j.DocumentException;ImportOrg.dom4j.DocumentHelper;Importorg.dom4j.Element;ImportOrg.dom4j.Node;ImportOrg.dom4j.io.SAXReader; Public classDom4jparsexml { Public Static voidMain (string[] args) {Saxreader reader=NewSaxreader (); File File=NewFile ("In.xml"); Try{Document doc=reader.read (file); Element Root=doc.getrootelement (); String Nodepath= "/business/list/item";        System.out.println (Bar (root, Nodepath)); } Catch(documentexception e) {e.printstacktrace (); }    }    //Traverse Root until it's next node     Public Staticstring Bar (Element root, string nodepath)throwsdocumentexception {Iterator i=Root.elementiterator (); Element element=NULL;  while(I.hasnext ()) {element=(Element) i.next (); if(Element.elementiterator (). Hasnext ()) {returnBar (element, Nodepath); } Else {                returnBarnode (element, Nodepath); }        }        return NULL; }    //to traverse node under element     Public Staticstring Barnode (node node, string nodepath) {StringBuffer buf=NewStringBuffer (); Try{Document Document=Documenthelper.parsetext (Node.getstringvalue ()); List List1=document.selectnodes (Nodepath);  for(Object object:list1) {Element n=(Element) object; List i201_=n.elements ();  for(Object object2:i201_) {Node I_node=(Node) object2; Buf.append (I_node.getname ()+ "="                            +i_node.getstringvalue (). Trim ()); }            }        } Catch(Exception e) {System.out.println ("Node.getstringvalue () ParseText Exception"); }        returnbuf.tostring (); }}
View Code

The above is the complete code.

Note In the XML above, element arg0 the following data is passed through <! [cdata[.]] > Surrounded by, <! [cdata[.]] The text interpreter in > is not executed (it is ignored by the parser), so you can tell that arg0 is a node element, and <! [cdata[.]] The contents of > are just plain text. So in the bar This method uses the iteration, mainly to get the plain text.

Second, the structure of the plain text, the text is a document, so in Barnode this method, the first to parse the text into a document. Then call Document.selectnodes (""); method to get a set of node,  and then traverse. Document also has Document.selectsinglenode ("") method, this method is directly to get a node nodes.

Reference: http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.