XML operations in Java: XML vs. String, reading XML document nodes and adding additions and deletions to XML nodes

Source: Internet
Author: User
Tags xml attribute

One, XML and string cross-transfer:

Using the DOM4J program makes it easy

// string goto XML String xmlstr = \"...";     Document document = Documenthelper.parsetext (XMLSTR);     // XML to String     Document document = ...;      = Document.asxml ();     // the XML Document here is Org.dom4j.Document  

Second, read the XML document node:

Package vastsum;import java.io.file;import java.util.iterator;import java.util.list;import org.dom4j.Document; Import Org.dom4j.documentexception;import org.dom4j.element;import org.dom4j.node;import org.dom4j.io.SAXReader;/** * Read the next XML document to get the Document object. */classExmple { Public Static voidMain (string[] args) throws documentexception {Saxreader reader=NewSaxreader (); Document Document= Reader.read (NewFile ("./src/contact.xml")); /** * How to manipulate node objects*/                //Get document root nodeElement root =document.getrootelement (); //the name of the output root tagSystem. out. println (Root.getname ()); //gets all child nodes under the root node (not child nodes that have been wrapped)list<element> list =root.elements (); //ways to traverse the list         for(Element e:list) {System. out. println (E.getname ()); }                //Gets the child nodes below the specified nodeElement Contactelem = root.element (" Contact");//The first thing you need to know is the node you want to manipulate. List<element> contactlist =contactelem.elements ();  for(Element e:contactlist) {System. out. println (E.getname ()); }                    //call the following to get the recursive function of the child node. getchildnodes (root); //Gets the first sub-label of the specified name under the current labelElement Conelem = root.element (" Contact"); System. out. println (Conelem.getname ()); //get a deeper label ( one layer at a level)Element Nameelem = root.element (" Contact"). Element ("name"); System. out. println (Nameelem.getname ()); }        //recursive query node function, output node name    Private Static voidgetchildnodes (Element elem) {System. out. println (Elem.getname ()); Iterator<Node> it =Elem.nodeiterator ();  while(It.hasnext ()) {node node=It.next (); if(node instanceof Element) {element E1=(Element) node;            Getchildnodes (E1); }        }    }   }

Third, the XML node attributes are added and censored

Package Vastsum;import Java.io.file;import java.io.filewriter;import java.util.iterator;import Org.dom4j.attribute;import Org.dom4j.document;import Org.dom4j.element;import Org.dom4j.io.SAXReader;import Org.dom4j.io.xmlwriter;import org.junit.Test;/** * Operation XML with DOM4J * Action XML file for XML attribute * Contact.xml **/ Public classattrdemo{@Test Public voidexmple () throws exception{//read the XML file to get the Document objectSaxreader reader =NewSaxreader (); Document Document= Reader.read (NewFile ("./src/contact.xml")); //get a Property object for a nodeElement Rootelem =document.getrootelement (); //Get root Node Property objectAttribute rootattr = Rootelem.attribute ("ID"); //gets the specified node Property objectElement Contactelem = rootelem.element (" Contact"); Attribute contactattr= Contactelem.attribute ("ID"); //gets the property name of the specified objectSystem. out. println (Rootattr.getname ()); System. out. println (Contactattr.getname ()); //gets the property value of the specified objectSystem. out. println (Contactattr.getvalue ()); System. out. println (Rootattr.getvalue ()); //Traverse all properties of a node         for(Iterator it =contactelem.attributeiterator (); It.hasnext ();) {Attribute conattr=(Attribute) it.next (); String Contxt=Conattr.getvalue (); String Conattrname=Conattr.getname (); System. out. println (conattrname+" = "+contxt); }        //set properties and values for a nodeContactelem.addattribute ("name","Zhangsan"); //Set (change) the value of a propertyAttribute nameattr = Contactelem.attribute ("name"); Nameattr.setvalue ("Lisi"); //to delete a specified property of a nodeContactelem.remove (nameattr); //writes the properties and values of a node to an XML documentXMLWriter writer =NewXMLWriter (NewFileWriter ("./src/contact.xml"));        Writer.write (document);                Writer.close (); //If the document has Chinese character encoding to be set, use the following statement:OutputFormat format =Outputformat.createprettyprint (); Format.setencoding ("GBK"); XMLWriter writer=NewXMLWriter (NewFileWriter ("./src/contact.xml"), format); }}

Below are the following dom4j:

DOM4J is the XML API for Java, which is used to read and write XML files. There are many scenarios where dom4j is used to read and write XML.

To use DOM4J development, you need to download the appropriate JAR file for import dom4j. Official website Download: HTTP://WWW.DOM4J.ORG/DOM4J-1.6.1/

After downloading the extract:

We just need to build the Dom4j-1.6.1.jar file into our development project.

Create a Lib file in your project, copy the Dom4j-1.6.1.jar file to Lib, and then right-click the Dom4j-1.6.1jar file. :


Click Add to Bulid the path to build into the project. Import succeeded:

XML operations in Java: XML vs. String, reading XML document nodes and adding additions and deletions to XML nodes

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.