This is an example of XML manipulation using the Java common-access DOM, which contains basic operations for querying, adding, modifying, deleting, and saving. A more complete description of an XML's entire operating process. Reference and learning for friends who are just getting started with Java XML operations.
Suppose you have an XML file: Test1.xml? XML version= "1.0" encoding= "UTF-8"?>
< books >
< book >
< name > Harry Potter </name >
< price > Ten </price >
< Memo > This is a very nice book. </Memo >
</book >
< book ID = "B02" >
< name > The </of the Kingdoms name >
< price > Ten </price >
< Memo > One of the four classics. </Memo >
</book >
< book ID = "B03" >
< name > margin </name >
< price > 6 </price >
< Memo > One of the four classics. </Memo >
</book >
< book ID = "B04" >
< name > Red Mansion </name >
< price > 5 </price >
< Memo > One of the four classics. </Memo >
</book >
</Books >
The following is for Test.java import java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Org.w3c.dom. * ;
Import org.xml.sax.SAXException;
Import Javax.xml.parsers. * ;
Import Javax.xml.transform. * ;
Import Javax.xml.transform.dom.DOMSource;
Import Javax.xml.transform.stream. * ;
Import Javax.xml.xpath. * ;
public class Test ... {
public static void Main (string[] args) ... {
Documentbuilderfactory factory=documentbuilderfactory.newinstance ();
Element Thebook=null, Theelem=null, Root=null;
Try ... {
Factory.setignoringelementcontentwhitespace (TRUE);
Documentbuilder Db=factory.newdocumentbuilder ();
Document Xmldoc=db.parse (New File ("Test1.xml"));
Root=xmldoc.getdocumentelement ();
---Start a new book----
Thebook=xmldoc.createelement ("book");
Theelem=xmldoc.createelement ("name");
Theelem.settextcontent ("new book");
Thebook.appendchild (Theelem);
Theelem=xmldoc.createelement ("Price");
Theelem.settextcontent ("20");
Thebook.appendchild (Theelem);
Theelem=xmldoc.createelement ("Memo");
Theelem.settextcontent ("The new book looks better.") ");
Thebook.appendchild (Theelem);
Root.appendchild (Thebook);
SYSTEM.OUT.PRINTLN ("---a new book begins----");