Java XML API Interface dom4j a simple example

Source: Internet
Author: User
Tags flush ibm developerworks log4j

Dom4j feels a bit like JS. Let's take a look at some basic usage of dom4j.

Basic usage

1. Gets the root node of the document.
Element Rootelm = Document.getrootelement ();
2. Get a single child node of a node.
Element memberelm=root.element ("member");//"Member" is a section roll call
3. Get the text of the node
String Text=memberelm.gettext ();
You can also use:
String text=root.elementtext ("name"); This is the text that gets the name byte point under the root node.

4. Get all the byte points named "member" under a node and traverse them.
List nodes = rootelm.elements ("member");

for (Iterator it = Nodes.iterator (); It.hasnext ();) {
   element elm = (Element) It.next ();
  /Do Something
}
5. Iterate through all the child nodes under a node.
             for (iterator It=root.elementiterator (); It.hasnext ();) {
                 element element = (Element) It.next ();
               //do something
           }
6. Add child nodes under a node.
Element Ageelm = newmemberelm.addelement ("Age");
7. Sets the node text.
Ageelm.settext ("29");
8. Deletes a node.
Parentelm.remove (Childelm);//Childelm is the node to be deleted, Parentelm is its parent node

You can also find an article on IBM Developerworks that evaluates the performance, functionality, and usability of the mainstream Java XML API, so you know that dom4j is excellent in any way. Now that more and more Java software is using dom4j to read and write XML, it is particularly worth mentioning that even Sun's JAXM is using DOM4J. This is already the jar package that must be used, and hibernate also uses it to read and write the configuration file.

example, reading and writing XML

Package com.test.transport.service;

Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.util.Iterator;
Import java.util.List;

Import Org.apache.log4j.Logger;
Import Org.dom4j.Attribute;
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;

public class Xmlservice {
public static Logger log = Logger.getlogger (Xmlservice.class);
Public Document GetDocument () {
Document doc = Documenthelper.createdocument ();
Doc.addcomment ("A simple demo");
Element root = Doc.addelement ("Persons");
Element P1 = root.addelement ("person");
P1.addattribute ("name", "Xiaohei");
P1.addattribute ("Age", "20");
P1.addattribute ("Sex", "male");
Element P2 = root.addelement ("person");
P2.addattribute ("name", "Xiaobai");
P2.addattribute ("Age", "21");
P2.addattribute ("Sex", "female");
return doc;
}
public void SaveDocument (Document doc,string filepath) {
OutputFormat format = Outputformat.createprettyprint ();
XMLWriter writer = null;
try {
writer = new XMLWriter (new FileWriter (New File (filepath)), format);
Writer.write (DOC);
Writer.flush ();
Writer.close ();
catch (IOException e) {
Log.error ("File Error");
E.printstacktrace ();
}
}
public static void Main (String args[]) {
Xmlservice service = new Xmlservice ();
Document doc = Service.getdocument ();
Service.savedocument (Doc, "Demo.xml");
}
}

2. Increase the Modification method

Package com.test.transport.service;

Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.util.Iterator;
Import java.util.List;

Import Org.apache.log4j.Logger;
Import Org.dom4j.Attribute;
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;

public class Xmlservice {
public static Logger log = Logger.getlogger (Xmlservice.class);
Public Document GetDocument () {
Document doc = Documenthelper.createdocument ();
Doc.addcomment ("A simple demo");
Element root = Doc.addelement ("Persons");
Element P1 = root.addelement ("person");
P1.addattribute ("name", "Xiaohei");
P1.addattribute ("Age", "20");
P1.addattribute ("Sex", "male");
Element P2 = root.addelement ("person");
P2.addattribute ("name", "Xiaobai");
P2.addattribute ("Age", "21");
P2.addattribute ("Sex", "female");
return doc;
}
public void SaveDocument (Document doc,string filepath) {
OutputFormat format = Outputformat.createprettyprint ();
XMLWriter writer = null;
try {
writer = new XMLWriter (new FileWriter (New File (filepath)), format);
Writer.write (DOC);
Writer.flush ();
Writer.close ();
catch (IOException e) {
Log.error ("File Error");
E.printstacktrace ();
}
}
Public Document editdocument (File inputfile) {
Saxreader Saxreader = new Saxreader ();
Document doc = null;
try {
doc = Saxreader.read (inputfile);
catch (Documentexception e) {
Log.error ("Read file error");
E.printstacktrace ();
}
list<attribute> list = Doc.selectnodes ("//persons/person/@name");
Iterator<attribute> iterator = List.iterator ();
while (Iterator.hasnext ()) {
attribute = Iterator.next ();
if (Attribute.getvalue (). EndsWith ("Xiaohei")) {
Attribute.setvalue ("Zhaodaoxiaohei");
}
}
List<element> List2 = doc.selectnodes ("//persons/person");
iterator<element> Iterator2 = List2.iterator ();
while (Iterator2.hasnext ()) {
Element element = Iterator2.next ();
Element.addtext ("5");
if (Element.attributevalue ("name"). Equals ("Xiaobai")) {
Element.addelement ("Grade"). AddText ("3");
}
}
return doc;
}
public static void Main (String args[]) {
Xmlservice service = new Xmlservice ();
Document doc = Service.getdocument ();
Service.savedocument (Doc, "Demo.xml");

Document document = Service.editdocument (new File ("Demo.xml"));
Service.savedocument (document, "Demo.xml");
}
}

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.