Java parsing XML (DOM method full)

Source: Internet
Author: User

Three mainstream technologies of Java processing XML and introduction http://www.ibm.com/developerworks/cn/xml/dm-1208gub/

This article is more detailed, the following I mainly introduce the DOM method to the XML file additions and deletions to change operations.

See http://blog.csdn.net/smcwwh/article/details/7183869 But because the typesetting is a bit messy, I tidy up what I need, as a later note ...

The biggest feature of DOM is: the implementation of the world standard, there are many programming languages to support this analytic way, and the method itself is simple and fast operation, very easy for beginners to master. It is handled by reading the XML as a tree-like structure into memory for manipulation and parsing, so that the application can modify the content and structure of the XML data, but at the same time because it needs to read the entire XML file into memory at the beginning of processing, it parses the XML of the large data volume File, you should be aware of the risk of memory leaks and program crashes.

Scope of application: Small XML file parsing, full parsing or most parsing of XML, need to modify XML tree content to generate your own object model

The XML data source used by the following code

<?XML version= "1.0" encoding= "UTF-8"?><Universityname= "PKU">    <Collegename= "C1">        <classname= "Class1">            <Studentname= "STU1"Sex= ' Male ' Age= "+" />            <Studentname= "STU2"Sex= ' Female ' Age= " the" />            <Studentname= "Stu3"Sex= ' Female ' Age= " the" />        </class>        <classname= "Class2">            <Studentname= "Stu4"Sex= ' Male ' Age= "+" />            <Studentname= "Stu5"Sex= ' Female ' Age= " the" />            <Studentname= "Stu6"Sex= ' Female ' Age= "+" />        </class>    </College>    <Collegename= "C2">        <classname= "Class3">            <Studentname= "Stu7"Sex= ' Male ' Age= " the" />        </class>    </College>    <Collegename= "C3">    </College></University>
View Code

Read the file

  Public Static voidRead () {documentbuilderfactory dbf=documentbuilderfactory.newinstance (); Try{Documentbuilder Builder=Dbf.newdocumentbuilder (); InputStream in= Testdom.class. getClassLoader (). getResourceAsStream ("Test.xml");//file nameDocument doc =Builder.parse (in); //Root <university>Element root =doc.getdocumentelement (); if(Root = =NULL)return; System.err.println (Root.getattribute ("Name")); //All College NodeNodeList collegenodes =root.getchildnodes (); if(Collegenodes = =NULL)return;  for(inti = 0; I < collegenodes.getlength (); i++) {Node College=Collegenodes.item (i); if(College! =NULL&& College.getnodetype () = =Node.element_node) {System.err.println ("\ T" + college.getattributes (). getNamedItem ("name"). Getnodevalue ()); //All class nodeNodeList classnodes =college.getchildnodes (); if(Classnodes = =NULL)Continue;  for(intj = 0; J < Classnodes.getlength (); J + +) {Node clazz=Classnodes.item (j); if(Clazz! =NULL&& Clazz.getnodetype () = =Node.element_node) {System.err.println ("\t\t" + clazz.getattributes (). getNamedItem ("name"). Getnodevalue ()); //All Student NodeNodeList studentnodes =clazz.getchildnodes (); if(Studentnodes = =NULL)Continue;  for(intk = 0; K < Studentnodes.getlength (); k++) {Node student=Studentnodes.item (k); if(Student! =NULL&& Student.getnodetype () = =Node.element_node) {System.err.print ("\t\t\t" + student.getattributes (). getNamedItem ("name"). Getnodevalue ()); System.err.print ("" + student.getattributes (). getNamedItem ("Sex"). Getnodevalue ()); System.err.println ("" + student.getattributes (). getNamedItem ("Age"). Getnodevalue ()); }                            }                        }                    }                }            }        } Catch(parserconfigurationexception e) {e.printstacktrace (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(saxexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }            }
View Code

Modify a node and write it to a file

    Public Static voidwrite () {documentbuilderfactory dbf=documentbuilderfactory.newinstance (); Try{Documentbuilder Builder=Dbf.newdocumentbuilder (); InputStream in= Testdom.class. getClassLoader (). getResourceAsStream ("Test.xml"); Document Doc=Builder.parse (in); //Root <university>Element root =doc.getdocumentelement (); if(Root = =NULL)return; //Modifying PropertiesRoot.setattribute ("name", "Tsu"); NodeList Collegenodes=root.getchildnodes (); if(Collegenodes! =NULL) {                 for(inti = 0; I <collegenodes.getlength ()-1; i++) {                    //Delete a nodeNode College =Collegenodes.item (i); if(College.getnodetype () = =Node.element_node) {String Collegename= College.getattributes (). getNamedItem ("name"). Getnodevalue (); if("C1". Equals (collegename) | | "C2". Equals (Collegename))                        {Root.removechild (college); } Else if("C3". Equals (Collegename)) {Element NewChild= Doc.createelement ("Class"); Newchild.setattribute ("Name", "C4");                        College.appendchild (NewChild); }                    }                }            }            //new NodeElement Addcollege = doc.createelement ("College"); Addcollege.setattribute ("Name", "C5");            Root.appendchild (Addcollege); Text text= Doc.createtextnode ("text");                        Addcollege.appendchild (text); //Save the modified document to a fileTransformerfactory transfactory =transformerfactory.newinstance (); Transformer Transformer=Transfactory.newtransformer (); Domsource Domsource=NewDomsource (DOC); File File=NewFile ("Src/dom-modify.xml"); if(File.exists ()) {file.delete ();            } file.createnewfile (); FileOutputStream out=Newfileoutputstream (file); Streamresult Xmlresult=NewStreamresult (out);            Transformer.transform (Domsource, Xmlresult);        System.out.println (File.getabsolutepath ()); } Catch(parserconfigurationexception e) {e.printstacktrace (); } Catch(saxexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } Catch(transformerconfigurationexception e) {e.printstacktrace (); } Catch(transformerexception e) {e.printstacktrace (); }    }}
View Code

Java parsing XML (DOM method full)

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.