Java generates and parses an instance code for XML format files and strings _java

Source: Internet
Author: User
Tags gettext object model stub xpath

1. Basic knowledge:
Java parsing XML generally has four methods: DOM, SAX, JDOM, dom4j.

2, the use of the introduction
1), DOM
(1) Introduction

The interface provided by the Org.w3c.dom, which reads the entire XML document into memory and constructs a DOM tree to operate on individual nodes (node). The advantage is that the entire document is always in memory, we can access any node at any time, and the traversal of the tree is a familiar operation, the disadvantage is memory, and must wait until all documents are read into memory to be processed.

(2) Sample code:

Copy Code code as follows:

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"?>
<root>
<TelePhone>
<type name= "Nokia" >
<price>599</price>
<operator>CMCC</operator>
</type>
<type name= "Xiaomi" >
<price>699</price>
<operator>ChinaNet</operator>
</type>
</TelePhone>
</root>



Copy Code code as follows:



Import Java.io.ByteArrayOutputStream;


Import Java.io.File;


Import Java.io.FileOutputStream;


Import java.io.IOException;


Import Java.io.StringReader;

Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import javax.xml.parsers.ParserConfigurationException;
Import Javax.xml.transform.Transformer;
Import javax.xml.transform.TransformerConfigurationException;
Import javax.xml.transform.TransformerException;
Import Javax.xml.transform.TransformerFactory;
Import Javax.xml.transform.dom.DOMSource;
Import Javax.xml.transform.stream.StreamResult;

Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList;
Import Org.xml.sax.InputSource;
Import org.xml.sax.SAXException;

public class Xmlhandler {


Public Xmlhandler () {





}





Public String Createxml () {


String xmlstr = null;


Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();


try {


Documentbuilder builder = Factory.newdocumentbuilder ();


Document document = Builder.newdocument ();


Document.setxmlversion ("1.0");





Element root = document.createelement ("root");


Document.appendchild (root);





Element telephone = document.createelement ("Telephone");





Element Nokia = document.createelement ("type");


Nokia.setattribute ("name", "Nokia");





Element Pricenokia = document.createelement ("price");


Pricenokia.settextcontent ("599");


Nokia.appendchild (Pricenokia);





Element Operatornokia = document.createelement ("operator");


Operatornokia.settextcontent ("CMCC");


Nokia.appendchild (Operatornokia);





Telephone.appendchild (Nokia);





Element Xiaomi = document.createelement ("type");


Xiaomi.setattribute ("name", "Xiaomi");





Element Pricexiaomi = document.createelement ("price");


Pricexiaomi.settextcontent ("699");


Xiaomi.appendchild (Pricexiaomi);





Element Operatorxiaomi = document.createelement ("operator");


Operatorxiaomi.settextcontent ("ChinaNet");


Xiaomi.appendchild (Operatorxiaomi);





Telephone.appendchild (Xiaomi);





Root.appendchild (telephone);





Transformerfactory transfactory = Transformerfactory.newinstance ();


Transformer Transformer = Transfactory.newtransformer ();


Domsource Domsource = new Domsource (document);





Export string


Bytearrayoutputstream BOS = new Bytearrayoutputstream ();


Transformer.transform (Domsource, New Streamresult (BOS));


Xmlstr = Bos.tostring ();





//-------


Save As File


File File = new file ("Telephone.xml");


if (!file.exists ()) {


File.createnewfile ();


}


FileOutputStream out = new FileOutputStream (file);


Streamresult Xmlresult = new Streamresult (out);


Transformer.transform (Domsource, Xmlresult);


//--------


catch (Parserconfigurationexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


}catch (Transformerconfigurationexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


}catch (Transformerexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


}catch (IOException e) {


TODO auto-generated Catch block


E.printstacktrace ();


}





return xmlstr;


}





public void Parserxml (String strxml) {


Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();


try {


Documentbuilder builder = Factory.newdocumentbuilder ();


StringReader sr = new StringReader (strxml);


InputSource is = new InputSource (SR);


Document doc = Builder.parse (IS);


Element rootelement = Doc.getdocumentelement ();


NodeList phones = rootelement.getelementsbytagname ("type");


for (int i = 0; i &lt; phones.getlength (); i++) {


Node type = Phones.item (i);


String Phonename = ((Element) type). getattribute ("name");


System.out.println ("Phone name =" +phonename);


NodeList properties = Type.getchildnodes ();


for (int j = 0; J &lt; Properties.getlength (); j + +) {


Node property = Properties.item (j);


String nodename = Property.getnodename ();


if (Nodename.equals ("price")) {


String price=property.getfirstchild (). Getnodevalue ();


System.out.println ("price=" +price);


else if (nodename.equals ("operator")) {


String operator=property.getfirstchild (). Getnodevalue ();


System.out.println ("operator=" +operator);


}


}


}


catch (Parserconfigurationexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


}catch (Saxexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


catch (IOException e) {


TODO auto-generated Catch block


E.printstacktrace ();


}


}





public static void Main (string[] args) {


Xmlhandler handler = new Xmlhandler ();


String XML = Handler.createxml ();


SYSTEM.OUT.PRINTLN (XML);


Handler.parserxml (XML);


}


}


(3) The difference between elements (element) and Node (node) (org.w3c.dom)
The node object is the primary data type for the entire Document object model and is the most basic object in the DOM, representing the abstract nodes in the document tree. However, in actual use, the node object is rarely used directly, but the node object's child object is used Element,attr,text, and so on.
An Element object, which represents one of the elements in an HTML or XML document, is the primary child of the node class, and can contain attributes in the element, so that there is a method of accessing its properties in the elements.
The element is inherited from node, and elements are a small scope definition, and it must be a node containing complete information that is an element, such as <div>...</div>. But a node is not necessarily an element, and an element must be a node.
Node has several subtypes: Element,text,attribute,rootelement,comment,namespace, etc.

2), SAX


3), JDOM

4), dom4j
(1) Introduction
DOM4J is currently the best in XML parsing (Hibernate, Sun Jaxm also uses dom4j to parse XML), merging many of the features that go beyond the representation of basic XML documents, including integrated XPath support, XML Schema support and event-based processing for large documents or streaming documents.
Add Jaxen.jar when using XPath, or you may receive the following error:

Copy Code code as follows:

Exception in thread "main" java.lang.noclassdeffounderror:org/jaxen/jaxenexception
At Org.dom4j.DocumentFactory.createXPath (documentfactory.java:230)
At Org.dom4j.tree.AbstractNode.createXPath (abstractnode.java:207)
At Org.dom4j.tree.AbstractNode.selectNodes (abstractnode.java:164)

(2) Sample code:

Copy Code code as follows:



Import Java.io.File;


Import Java.io.FileWriter;


Import java.io.IOException;


Import Java.io.StringReader;


Import Java.io.StringWriter;


Import java.util.List;

Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;
Import Org.dom4j.io.OutputFormat;
Import Org.dom4j.io.SAXReader;
Import Org.dom4j.io.XMLWriter;
Import Org.xml.sax.InputSource;

public class Xmlhandler {

Public Xmlhandler () {


TODO auto-generated Constructor stub


}





Public String Createxml () {


String strxml = null;


Document document = Documenthelper.createdocument ();


Element root = document.addelement ("root");





Element phone = root.addelement ("Telephone");





Element Nokia = phone.addelement ("type");


Nokia.addattribute ("name", "Nokia");


Element Price_nokia = nokia.addelement ("price");


Price_nokia.addtext ("599");


Element Operator_nokia = nokia.addelement ("operator");


Operator_nokia.addtext ("CMCC");





Element Xiaomi = phone.addelement ("type");


Xiaomi.addattribute ("name", "Xiaomi");


Element Price_xiaomi = xiaomi.addelement ("price");


Price_xiaomi.addtext ("699");


Element Operator_xiaomi = xiaomi.addelement ("operator");


Operator_xiaomi.addtext ("ChinaNet");





//--------


StringWriter STRWTR = new StringWriter ();


OutputFormat format = Outputformat.createprettyprint ();


Format.setencoding ("UTF-8");


XMLWriter XMLWriter =new XMLWriter (STRWTR, format);


try {


Xmlwriter.write (document);


catch (IOException E1) {


TODO auto-generated Catch block


E1.printstacktrace ();


}


Strxml = Strwtr.tostring ();


//--------





//-------


Strxml=document.asxml ();


//------





//-------------


File File = new file ("Telephone.xml");


if (file.exists ()) {


File.delete ();


}


try {


File.createnewfile ();


XMLWriter out = new XMLWriter (new FileWriter (file));


Out.write (document);


Out.flush ();


Out.close ();


catch (IOException e) {


TODO auto-generated Catch block


E.printstacktrace ();


}


//--------------





return strxml;


}





public void Parserxml (String strxml) {


Saxreader reader = new Saxreader ();


StringReader sr = new StringReader (strxml);


InputSource is = new InputSource (SR);


try {


Document document = Reader.read (IS);





Element root = Document.getrootelement ();





Get element


list&lt;element&gt; phonelist = root.elements ("Telephone");


list&lt;element&gt; typelist = phonelist.get (0). Elements ("type");


for (int i=0;i&lt;typelist.size (); i++) {


Element element = Typelist.get (i);


String phonename = element.attributevalue ("name");


System.out.println ("phonename =" +phonename);


Get all Element


list&lt;element&gt; childlist = element.elements ();


for (int j=0;j&lt;childlist.size (); j + +) {


Element e = Childlist.get (j);


System.out.println (E.getname () + "=" +e.gettext ());


}


}


catch (Documentexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


}


}





public void Parserxmlbyxpath (String strxml) {


Saxreader reader = new Saxreader ();


StringReader sr = new StringReader (strxml);


InputSource is = new InputSource (SR);


try {


Document document = Reader.read (IS);


List List = Document.selectnodes ("/root/telephone/type");


for (int i=0;i&lt;list.size (); i++) {


Element e = (element) list.get (i);


System.out.println ("Phonename=" +e.attributevalue ("name"));


List List1 = E.selectnodes ("./*");


for (int j=0;j&lt;list1.size (); j + +) {


Element e1 = (Element) List1.get (j);


System.out.println (E1.getname () + "=" +e1.gettext ());


}


}


catch (Documentexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


}


}

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Xmlhandler handler = new Xmlhandler ();
String Strxml=handler.createxml ();
System.out.println (strxml);
Handler.parserxml (strxml);
System.out.println ("-----------");
Handler.parserxmlbyxpath (strxml);
}

}

5) XPATH
(1) Introduction
XPath is a language that looks for information in an XML document. XPath is used to navigate through elements and attributes in an XML document.
Specific syntax introduction reference: Http://w3school.com.cn/xpath/index.asp

(2) Sample code:

Copy Code code as follows:



Import java.io.IOException;


Import Java.io.StringReader;

Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import javax.xml.parsers.ParserConfigurationException;
Import Javax.xml.xpath.XPath;
Import javax.xml.xpath.XPathConstants;
Import javax.xml.xpath.XPathExpression;
Import javax.xml.xpath.XPathExpressionException;
Import Javax.xml.xpath.XPathFactory;

Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList;
Import Org.xml.sax.InputSource;
Import org.xml.sax.SAXException;

public class Xmlhandler {

Public Xmlhandler () {


TODO auto-generated Constructor stub


}





public void Parserxml (String strxml) {


Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();


try {


Documentbuilder builder = Factory.newdocumentbuilder ();


StringReader sr = new StringReader (strxml);


InputSource is = new InputSource (SR);


Document doc = Builder.parse (IS);





Xpathfactory xfactory = Xpathfactory.newinstance ();


XPath XPath = Xfactory.newxpath ();


XPathExpression expr = xpath.compile ("/root/telephone/type");


NodeList phones = (nodelist) expr.evaluate (Doc, Xpathconstants.nodeset);


for (int i = 0; i &lt; phones.getlength (); i++) {


Node type = Phones.item (i);


String Phonename = ((Element) type). getattribute ("name");


System.out.println ("Phone name =" +phonename);


XPathExpression expr1 = Xpath.compile ("./*");


NodeList list = (nodelist) expr1.evaluate (type, xpathconstants.nodeset);


for (Int J =0;j&lt;list.getlength (); j + +) {


Element e1 = (Element) List.item (j);


System.out.println (E1.getnodename () + "=" +e1.gettextcontent ());


}





}


catch (Parserconfigurationexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


}catch (Saxexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


catch (IOException e) {


TODO auto-generated Catch block


E.printstacktrace ();


}catch (Xpathexpressionexception e) {


TODO auto-generated Catch block


E.printstacktrace ();


}

}


/**


* @param args


*/


public static void Main (string[] args) {


TODO auto-generated Method Stub


String strxml= "&lt;?xml version=\" 1.0\ "encoding=\" utf-8\ "standalone=\" no\ "?&gt;" +


"&lt;root&gt;" +


"&lt;TelePhone&gt;" +


"&lt;type name=\" Nokia\ "&gt;" +


"&lt;price&gt;599&lt;/price&gt;" +


"&lt;operator&gt;CMCC&lt;/operator&gt;" +


"&lt;/type&gt;" +


"&lt;type name=\" xiaomi\ "&gt;" +


"&lt;price&gt;699&lt;/price&gt;" +


"&lt;operator&gt;ChinaNet&lt;/operator&gt;" +


"&lt;/type&gt;" +


"&lt;/TelePhone&gt;" +


"&lt;/root&gt;";


Xmlhandler handler = new Xmlhandler ();


Handler.parserxml (strxml);


}

}

PS: Here again for you to provide several online tools on XML operations for your reference to use:

Online Xml/json Mutual Conversion tool:
Http://tools.jb51.net/code/xmljson

Online format xml/on-line compression of XML:
Http://tools.jb51.net/code/xmlformat

XML online compression/formatting tool:
http://tools.jb51.net/code/xml_format_compress

Related Article

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.