Write content to an XML document

Source: Internet
Author: User

 PackageGz.itcast.a_dom4j_write;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportOrg.dom4j.Document;ImportOrg.dom4j.io.SAXReader;ImportOrg.dom4j.io.XMLWriter;/** * First write content to XML document * @author APPle * */ Public  class Demo1 {     Public Static void Main(string[] args)throwsexception{//One, read or create a Document object        //Read XM file for DAY07 projectDocument doc =NewSaxreader (). Read (NewFile ("./src/contact.xml"));//Second, modify the Document object content        //Third, write the modified document object into the XML document        //Specify the location of the file outputFileOutputStream out =NewFileOutputStream ("E:/contact.xml");//1. Creating a write-out objectXMLWriter writer =NewXMLWriter (out);//2. Writing ObjectsWriter.write (DOC);//3. Closing a streamWriter.close (); }}
 PackageGz.itcast.a_dom4j_write;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportOrg.dom4j.Document;ImportOrg.dom4j.io.OutputFormat;ImportOrg.dom4j.io.SAXReader;ImportOrg.dom4j.io.XMLWriter;/** * Discuss the details of writing the content to the XML document * @author APPle * * * * Public  class Demo2 {    /** * @param args * *     Public Static void Main(string[] args)throwsexception{Document doc =NewSaxreader (). Read (NewFile ("./src/contact.xml"));//Specify the location of the file outputFileOutputStream out =NewFileOutputStream ("E:/contact.xml");/** * 1. Specify the format written out */OutputFormat format = Outputformat.createcompactformat ();//compact format. Remove whitespace wrapping. When the project is on the line        //outputformat format = Outputformat.createprettyprint ();///beautiful formats. There are spaces and line breaks. When developing and debugging        /** * 2. Specifies that the encoding of the generated XML document * also affects the encoding of the XML document when it is saved and the encoding encoding of the XML document declaration (encoding at XML parsing) * Conclusion: Using this method to produce         XML document to avoid Chinese garbled problems. */Format.setencoding ("Utf-8");//1. Creating a write-out objectXMLWriter writer =NewXMLWriter (Out,format);//2. Writing ObjectsWriter.write (DOC);//3. Closing a streamWriter.close (); }}
 PackageGz.itcast.a_dom4j_write;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportOrg.dom4j.Attribute;ImportOrg.dom4j.Document;ImportOrg.dom4j.DocumentHelper;ImportOrg.dom4j.Element;ImportOrg.dom4j.io.OutputFormat;ImportOrg.dom4j.io.SAXReader;ImportOrg.dom4j.io.XMLWriter;ImportOrg.junit.Test;/** * Modify XML content * Add: Document, Tag, properties * Modify: Attribute value, text * Delete: Tag, attribute * @author APPle * */ Public  class Demo3 {    /** * Added: Documents, tags, attributes */    @Test     Public void test1()throwsexception{/** * 1. Create a document * /Document doc = Documenthelper.createdocument ();/** * 2. Add label * /Element Rootelem = doc.addelement ("ContactList");//doc.addelement ("ContactList");Element Contactelem = rootelem.addelement ("Contact"); Contactelem.addelement ("Name");/** * 3. Add attributes * /Contactelem.addattribute ("id","001"); Contactelem.addattribute ("Name","Eric");//write out the modified document object to the XML documentFileOutputStream out =NewFileOutputStream ("F:/contact.xml");        OutputFormat format = Outputformat.createprettyprint (); Format.setencoding ("Utf-8"); XMLWriter writer =NewXMLWriter (Out,format);        Writer.write (DOC);    Writer.close (); }/** * Modify: Attribute value, text * @throws Exception */    @Test     Public void test2()throwsexception{Document doc =NewSaxreader (). Read (NewFile ("./src/contact.xml"));/** * Scenario One: Modify the property value 1. Get the Label Object 2. Get Property Object 3. Modify the property value * /        //1.1 Get Tag Object        /* Element Contactelem = doc.getrootelement (). Element ("contact");        1.2 Get the Attribute object Attribute idattr = Contactelem.attribute ("id");        1.3 Modify the attribute value Idattr.setvalue ("003"); */        /** * Scenario Two: Modifying attribute values */        //1.1 Get Tag Object        /* Element Contactelem = doc.getrootelement (). Element ("contact");        1.2 Modify the property value Contactelem.addattribute ("id", "004") by adding a property of the same name. */        /** * Modify Text 1. Get the Label Object 2. Modify Text * /Element Nameelem = Doc.getrootelement (). Element"Contact"). Element ("Name"); Nameelem.settext ("John Doe"); FileOutputStream out =NewFileOutputStream ("E:/contact.xml");        OutputFormat format = Outputformat.createprettyprint (); Format.setencoding ("Utf-8"); XMLWriter writer =NewXMLWriter (Out,format);        Writer.write (DOC);    Writer.close (); }/** * Delete: Tags, properties * @throws Exception */    @Test     Public void test3()throwsexception{Document doc =NewSaxreader (). Read (NewFile ("./src/contact.xml"));/** * 1. Delete Label 1.1 get Label Object 1.2 Delete Tag Object * /        //1.1 Get Tag Object        / * Element Ageelem = doc.getrootelement (). Element ("contact"). Element ("age");        1.2 Delete Tag object Ageelem.detach ();        Ageelem.getparent (). Remove (Ageelem); */        /** * 2. Delete Attribute 2.1 Get Property Object 2.2 Delete attribute * /        //2.1 Get Property Object        //Get a second contact labelElement Contactelem = (Element) doc.getrootelement (). Elements (). Get (1);//2.2 Get Property ObjectAttribute idattr = Contactelem.attribute ("id");//2.3 Deleting PropertiesIdattr.detach ();//idattr.getparent (). Remove (idattr);FileOutputStream out =NewFileOutputStream ("E:/contact.xml");        OutputFormat format = Outputformat.createprettyprint (); Format.setencoding ("Utf-8"); XMLWriter writer =NewXMLWriter (Out,format);        Writer.write (DOC);    Writer.close (); }}
 PackageGz.itcast.a_dom4j_write;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.util.Iterator;ImportOrg.dom4j.Document;ImportOrg.dom4j.DocumentHelper;ImportOrg.dom4j.Element;ImportOrg.dom4j.io.OutputFormat;ImportOrg.dom4j.io.SAXReader;ImportOrg.dom4j.io.XMLWriter;ImportOrg.junit.Test;/** * 1. Use the DOM4J API to generate the following XML file <students><student id= "1" > <name> Zhang San </name> <gender > Male </gender> <grade> Computer Class 1 </grade> <address> Guangzhou tianhe </address></Student><    Student id= "2" > <name> John Doe </name> <gender> Women </gender> <grade> Computer Class 2 </grade> <address> Guangzhou yuexiu </address></student></students>2. Change the name of the student with ID 2 to "Wang Li" 3. Delete student with ID 2 * @ Author APPle * * * * Public  class Demo4 {    /** * 1. Generate the specified XML document * @throws Exception */    @Test     Public void test1()throwsexception{//1. Memory Creation XML DocumentDocument doc = Documenthelper.createdocument ();//2. Writing contentElement Rootelem = doc.addelement ("Students");//2.1 Add TagElement studentElem1 = rootelem.addelement ("Student");//2.2 Adding PropertiesStudentelem1.addattribute ("id","1");//2.3 Add tags while setting the textStudentelem1.addelement ("Name"). SetText ("Zhang San"); Studentelem1.addelement ("Gender"). SetText ("Male"); Studentelem1.addelement ("Grade"). SetText ("Computer Class 1"); Studentelem1.addelement ("Address"). SetText ("Guangzhou Tianhe");//2.1 Add TagElement studentElem2 = rootelem.addelement ("Student");//2.2 Adding PropertiesStudentelem2.addattribute ("id","2");//2.3 Add tags while setting the textStudentelem2.addelement ("Name"). SetText ("John Doe"); Studentelem2.addelement ("Gender"). SetText ("female"); Studentelem2.addelement ("Grade"). SetText ("Computer Class 2"); Studentelem2.addelement ("Address"). SetText ("Guangzhou Yuexiu");//3. Content written out to an XML file        //3.1 Output PositionFileOutputStream out =NewFileOutputStream ("E:/student.xml");//3.2 Specifying formatsOutputFormat format = Outputformat.createprettyprint ();//Set encodingFormat.setencoding ("Utf-8"); XMLWriter writer =NewXMLWriter (Out,format);//3.3 Write ContentWriter.write (DOC);//3.4 Closing ResourcesWriter.close (); }/** * 2. Change the name of the student with ID 2 * @throws Exception */    @Test     Public void test2()throwsexception{//1. Query to a student with ID 2Document doc =NewSaxreader (). Read (NewFile ("E:/student.xml"));//1.1 Find all the student tagsIterator<element> it = doc.getrootelement (). Elementiterator ("Student"); while(It.hasnext ()) {Element Stuelem = It.next ();//1.2 Query ID for student tag            if(Stuelem.attributevalue ("id"). Equals ("2") {Stuelem.element ("Name"). SetText ("Wang Li"); Break; }        }//3.1 Output PositionFileOutputStream out =NewFileOutputStream ("E:/student.xml");//3.2 Specifying formatsOutputFormat format = Outputformat.createprettyprint ();//Set encodingFormat.setencoding ("Utf-8"); XMLWriter writer =NewXMLWriter (Out,format);//3.3 Write ContentWriter.write (DOC);//3.4 Closing ResourcesWriter.close (); }/** * 3. Delete student with ID 2 * @throws Exception */    @Test     Public void test3()throwsexception{//1. Query to a student with ID 2Document doc =NewSaxreader (). Read (NewFile ("E:/student.xml"));//1.1 Find all the student tagsIterator<element> it = doc.getrootelement (). Elementiterator ("Student"); while(It.hasnext ()) {Element Stuelem = It.next ();//1.2 Query ID for student tag            if(Stuelem.attributevalue ("id"). Equals ("2")){//1.3 Delete the student tagStuelem.detach (); Break; }        }//3.1 Output PositionFileOutputStream out =NewFileOutputStream ("E:/student.xml");//3.2 Specifying formatsOutputFormat format = Outputformat.createprettyprint ();//Set encodingFormat.setencoding ("Utf-8"); XMLWriter writer =NewXMLWriter (Out,format);//3.3 Write ContentWriter.write (DOC);//3.4 Closing ResourcesWriter.close (); }}

Write content to an XML document

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.