The parsing practice of Java EE on XML

Source: Internet
Author: User

The first is the XML file, which I saved in the SRC directory.

Exam.xml

<?xml version= "1.0" encoding= "UTF-8"?><exam>   <student idcard= "111" examid= "222" >     < Name> Zhang San </name>      <location> Shenyang </location>      <grade>89</grade>   </ student>    <student idcard= "333" examid= "444" >     <name> John Doe </name>      <location> Dalian </location>      <grade>97</grade>   </student>    <student idcard= "555" examid= " 666 ">     <name name=" ww "> Harry </name>      <location> Wuhan </location>      <grade> 92</grade>   </student> </exam>

First, using the DOM parsing of Jaxp to implement CRUD

Package Xml_csdn_example;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.transformerfactory;import Javax.xml.transform.dom.domresult;import Javax.xml.transform.dom.domsource;import Javax.xml.transform.stream.streamresult;import Org.junit.test;import Org.w3c.dom.document;import Org.w3c.dom.element;import Org.w3c.dom.node;import Org.w3c.dom.nodelist;public class XML_JAXP {@Testpublic void test1 () throws Exception {/* * query all element tags */document doc = read ();  Node item = doc.getelementsbytagname ("Exam"). Item (0); Getchilder (item); Using recursive function}private void Getchilder (Node item) {//TODO auto-generated method StubSystem.out.println (Item.getnodename () ); NodeList list = Item.getchildnodes (); for (int i=0;i<list.getlength (); i++) {Node node = List.item (i); Getchilder (node) ;}} 2. Query a node@Testpublic void test02 () throws Exception{document doc = Read (); Element selement = (Element) doc.getelementsbytagname ("Student"). Item (0); Element celement = (Element) selement.getelementsbytagname ("name"). Item (0); System.out.println (Selement.getattribute ("Idcard")); System.out.println (Selement.getattribute ("Examid")); System.out.println (Celement.gettextcontent ());} 3. Modify a node//3.1 add a student@testpublic void test03 () throws Exception{document doc = Read (); Element element = doc.createelement ("student"), Element.setattribute ("Idcard", "777"), Element.setattribute ("Examid"); , "888");//3.3 add city and other attributes to the state element celement = doc.createelement ("name"); Celement.settextcontent ("Mao June Feng"); Element.appendchild (celement); Node root = doc.getelementsbytagname ("Exam"). Item (0); Root.appendchild (element); write ();}
<span style= "White-space:pre" ></span>//delete @testpublic void test04 () throws Exception{document doc = Read (); Element selement = (Element) doc.getelementsbytagname ("Student"). Item (1); element name = (Element) selement.getelementsbytagname ("name"). Item (0); Selement.removechild (name); write ();} Read Operation private Document read () throws Exception {//Find XML, first create Documentbuilderfactory instance documentbuilderfactory Factory = Documentbuilderfactory.newinstance ();//Documentbuilderfactory instance to create Documentbuilder instance documentbuilder Builder = Factory.newdocumentbuilder ()//The Parse method is called through the Documentbuilder instance to read the XML file document doc = Builder.parse ("Src/exam.xml") ; return doc;} Write Operation private void Write () throws Exception {//1, creating an instance through Transformerfactory, calling newinstance method Transformerfactory Factory = Transformerfactory.newinstance ();///2. Create Newtransformer object by Transformerfactory instance Transformer transformer = Factory.newtransformer ();//3, using the transform method of transformer object to modify the XML file Transformer.transform (new Domsource (), New Streamresult ("sRc/exam.xml "));}} 

Second, the use of dom4j tools to implement CRUD

Package Xml_csdn_example;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.unsupportedencodingexception;import Java.util.list;import Org.dom4j.document;import Org.dom4j.documentexception;import Org.dom4j.element;import Org.dom4j.io.outputformat;import Org.dom4j.io.saxreader;import Org.dom4j.io.xmlwriter;import Org.junit.test;public class XML_DOM4J {//query, It is also possible to use the recursive method @testpublic void test01 () throws Exception {//TODO auto-generated method Stubdocument doc = Read (); Element root = Doc.getrootelement (); List List = Root.elements (); for (int i=0;i<list.size (); i++) {System.out.println (List.get (i));}} Added @testpublic void test02 () throws Exception {Document doc = read (); Element root = Doc.getrootelement (); Element student = root.addelement ("student"), Student.addattribute ("Idcard", "777"), Student.addattribute ("Examid", " 888 "), student.addelement (" name "). AddText (" Mao June Feng "), Student.addelement (" location "). AddAttribute (" Address "," Longxian "). AddText ("Wengyuan"); Student.addelement ("GrAde "). AddText (" + "); write (doc);} Modify @testpublic void test03 () throws Exception {Document doc = read (); Element root = Doc.getrootelement (); element element = (Element) root.elements (). Get (3);//element.addattribute ("Idcard", "123"); element name = (element) element.elements (). get (0); Name.settext ("Tyrannosaurus rex"); write (DOC); Delete @testpublic void test04 () throws Exception {Document doc = read (); Element root = Doc.getrootelement (); element element = (Element) root.elements (). Get (3);//(Element) element.elements (). Get (1)). Attribute ("Address"). Detach (); Element.detach (); write (doc);} Reading public Document read () throws Exception{saxreader reader = new Saxreader ();D ocument doc = Reader.read ("Src/ex") using dom4j Am.xml "); return doc;} Modified with dom4j private void write (Document doc) throws Exception {//TODO auto-generated method Stubxmlwriter writer = new X Mlwriter (New FileOutputStream ("Src/exam.xml"), Outputformat.createprettyprint ()); Writer.write (doc); Writer.close ( );}}

Third, the use of XML parsing method of Sax parsing

1) The first way is to directly query all the tags

Package Xml_csdn_example;import Java.io.ioexception;import Javax.xml.parsers.saxparser;import Javax.xml.parsers.saxparserfactory;import Org.junit.test;import Org.xml.sax.attributes;import Org.xml.sax.saxexception;import Org.xml.sax.xmlreader;import Org.xml.sax.helpers.defaulthandler;public class XML_ SAX01 {//sax read @testpublic void Read () throws Exception {//TODO auto-generated method Stubsaxparserfactory factory = Saxpa Rserfactory.newinstance (); SAXParser saxparser = Factory.newsaxparser (); XMLReader reader = Saxparser.getxmlreader (); mycontent m = new mycontent (); Reader.setcontenthandler (m); Reader.parse ("Src/exam.xml"); System.out.println (M.getpath ());}} Class Mycontent extends defaulthandler{private string path = "";p ublic string GetPath () {return path;} @Overridepublic void Startelement (String uri, String localname, String Qname,attributes Attributes) throws Saxexception { Path + = "<" +qname;for (int i =0;i<attributes.getlength (); i++) {String value = Attributes.getvalue (i); String name = Attributes.getqname (i);p ath + = "" + name + "=\" "+ Value +" \ "";} Path + = ">";} @Overridepublic void characters (char[] ch, int start, int length) throws saxexception {path +=new String (ch,start,length); } @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {path + = "</" + QName + ">";}}

2) The second way is to encapsulate the object and manipulate it with the object

Package Xml_example_xpath;import Java.util.arraylist;import Java.util.list;import javax.smartcardio.atr;import Javax.xml.parsers.saxparser;import Javax.xml.parsers.saxparserfactory;import Org.junit.Test;import Org.xml.sax.attributes;import Org.xml.sax.saxexception;import Org.xml.sax.xmlreader;import org.xml.sax.helpers.defaulthandler;/* * About autonomous operation of XML all elements */public class Demo5 {@Testpublic void Saxjiexi () throws Exception{saxparserfactory factory = Saxparserfactory.newinstance (); SAXParser saxparser = Factory.newsaxparser (); XMLReader reader = Saxparser.getxmlreader ();//mycontent handler = new mycontent ();//reader.setcontenthandler (handler) ; Reader.parse ("./src/exam.xml");//system.out.println (Handler.getpath ());} @Testpublic void Saxentity () throws Exception{saxparserfactory factory = Saxparserfactory.newinstance (); SAXParser saxparser = Factory.newsaxparser (); XMLReader reader = Saxparser.getxmlreader (); Mycontent handler = new mycontent (); Reader.setcontenthandler (handler); Reader.parse ("./src/Exam.xml "); list<student> list = Handler.getlist (); for (Student student:list) {System.out.println (Student);}}} Class Mycontent extends Defaulthandler{private Student student;private list<student> List = new arraylist< Student> ();p rivate String curtag;public list<student> getList () {return List;} @Overridepublic void Startelement (String uri, String localname, String Qname,attributes Attributes) throws Saxexception { Curtag=qname;if ("Student". Equals (QName)) {student = new student (); String Idcard = Attributes.getvalue ("Idcard"); String Examid = Attributes.getvalue ("Examid"); Student.setexamid (Examid); Student.setidcard (Idcard);}} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {Curtag = ""; if ("Student". Equals (QName)) {List.add (student);}} @Overridepublic void characters (char[] ch, int start, int length) throws Saxexception {string content = new String (CH, star T, length), if ("Name". Equals (Curtag)) {student.setname (content);} if ("Location ". Equals (Curtag)) {student.setlocation (content);} if ("Grade". Equals (Curtag)) {Student.setgrade (content);}}}

Through the two days of the comparison of the system of XML learning, understand the two analytic methods and functions, but also as XML has laid a relatively solid foundation


The parsing practice of Java EE on XML

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.