XML series: (7) XML parsing-dom4j Dom parsing method update xml

Source: Internet
Author: User

Dom4j tool, is unofficial, not in the JDK.

Steps to use:

1) Import the core package of dom4j. Dom4j-1.6.1.jar

2) write the code dom4j read the XML file


1. Update xml


1.1. Write content to XML document
Package Com.rk.xml.g_dom4j_write;import Java.io.file;import Java.io.fileoutputstream;import org.dom4j.Document; Import Org.dom4j.io.saxreader;import org.dom4j.io.xmlwriter;/** * First write content to XML document * @author RK * */public class Demo01{publ IC static void Main (string[] args) throws exception{//one, reads or creates a Document Object document DOC = new Saxreader (). Read (New File ("./ Src/animals.xml "));//second, modify the Document object content//third, write the modified document object to the XML document//Specify the location of the file output FileOutputStream OutStream = new FileOutputStream ("D:/rk/result.xml");//1. Create write-out object XMLWriter writer = new XMLWriter (outstream);//2. Write Document Object Writer.write (DOC);//3. Close Stream Writer.close (); System.out.println ("Execution is over!") ");}}


1.2. Write down the details of the content to the XML document
Package com.rk.xml.g_dom4j_write;import java.io.file;import java.io.fileoutputstream;import  org.dom4j.Document;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import  org.dom4j.io.xmlwriter;/** *  discusses the details of writing content to XML documents  *  @author  RK * */public  Class demo02{public static void main (String[] args)  throws exception{ Document doc = new saxreader (). Read (New file ("./src/animals2.xml"));/** *  1. Specify the written format  *///outputformat format = outputformat.createcompactformat ();// Compact format. Removes whitespace wrapping. When the project is on line Outputformat format = outputformat.createprettyprint ();// Nice format. There are spaces and line breaks./** * 2 when developing and debugging. Specifies the encoding of the generated XML document  *     also affects the encoding of the XML document when it is saved    Encoding encoding for   xml document declaration (encoding at XML parsing)  *     conclusion:  Use this method to generate XML documents to avoid Chinese garbled problems.  */format.setencoding ("UTF-8");//Specify the location of the file output FileoutputstreaM outstream = new fileoutputstream ("D:/rk/result.xml");//1. Create a write-out object Xmlwriter writer  = new xmlwriter (Outstream, format);//2. Write the Document Object Writer.write (DOC);//3. Close Stream Writer.close ( ); System.out.println ("Execution is over!") ");}}



1.3. Modify the XML content: Add, modify, delete
Package com.rk.xml.g_dom4j_write;import java.io.file;import java.io.fileoutputstream;import  org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Node;import  org.dom4j.element;import org.dom4j.attribute;import org.dom4j.text;import  org.dom4j.io.saxreader;import org.dom4j.io.xmlwriter;import org.dom4j.io.outputformat;import  org.junit.test;/** *  Modify XML Content  *  add: document, Tag  , Properties  *  Modify: Attribute value, text  *  Delete: label, Properties  *  @author  RK * */public class Demo03{/** *  add: Document, Tag  , properties  */@Testpublic  void testadd ()  throws exception{//1. Creating a document document doc =  Documenthelper.createdocument ();//2. Add Label element rootelement = doc.addelement ("ContactList"); Element contactelement = rootelement.addelement ("contact"); Element nameelement = contactelement.addelement ("Name"); Nameelement.setteXT ("Xiaoming");//3. Add attribute Contactelement.addattribute ("id",  "c001"); Contactelement.addattribute ("Region",  "Beijing )//write the modified document object to the XML document Fileoutputstream out = new fileoutputstream ("d:/rk/ Contact.xml "); Outputformat format = outputformat.createprettyprint (); Format.setEncoding (" Utf-8 " ); Xmlwriter writer = new xmlwriter (Out,format); Writer.write (doc); Writer.close (); System.out.println ("Execution is over!") ");} /** *  Modify: Attribute value, text  */@Testpublic  void testmodify ()  throws exception{document  doc = new saxreader (). Read (New file ("./src/animals.xml"));/** *  scheme one:  Modify the property value    1. Gets the Label object  2.  3. Modify the property value  *///1.1   get the Label object element  Catelement = doc.getrootelement (). Element ("Cat");//1.2  Gets the Property object attribute catattr =  catelement.attribute ("id");//1.3  Modify the property value Catattr.setvalue ("C100");/** *  scenario two:  Modify the property value  *///2.1 &nBSP; element dogelement = doc.getrootelement (). Element ("Dog");//2.2  by adding a property of the same name, Modify the property value Dogelement.addattribute ("id",  "d100");/** *  Modify the text  1. Gets the Label object  2. Modify Text  */element  nameelement = doc.getrootelement (). Element ("Cat"). Element ("Home"); Nameelement.settext ("Sixth Universe"); Fileoutputstream out = new fileoutputstream ("D:/rk/animals.xml"); OutputFormat format  = outputformat.createprettyprint (); Format.setencoding ("Utf-8"); Xmlwriter writer = new xmlwriter (Out,format); Writer.write (doc); Writer.close (); System.out.println ("Execution is over!") ");} /** *  Delete: Tags, properties  */@Testpublic  void testdelete ()  throws exception{document  doc = new saxreader (). Read (New file ("./src/animals.xml"));/** * 1. deleting tags      1.1  get Tag Object   1.2  Delete Tag object      *///  1.1  get Tagged object element nameelement&nBsp;= doc.getrootelement (). Element ("Cat"). Element ("Home");//1.2  Delete tag object Nameelement.detach ();// Nameelement.getparent (). Remove (nameelement),/** * 2. Delete Property    2.1 Get Property Object   2.2   Delete attribute  */element catelement = doc.getrootelement (). Element ("Cat");//2.1 Get Property object attribute  idattr = catelement.attribute ("id");//2.2  delete attribute Idattr.detach ();//idattr.getparent (). Remove (IDATTR); Fileoutputstream out = new fileoutputstream ("D:/rk/animals.xml"); OutputFormat format  = outputformat.createprettyprint (); Format.setencoding ("Utf-8"); Xmlwriter writer = new xmlwriter (Out,format); Writer.write (doc); Writer.close (); System.out.println ("Execution is over!") ");}}



2. Mind Mapping

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/80/0F/wKioL1c2J2mQaTfAAAHmv1_GZM0598.png "width=" 1200 " height= "alt=" "Wkiol1c2j2mqatfaaahmv1_gzm0598.png"/>




XML series: (7) XML parsing-dom4j Dom parsing method update 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.