Java Tool class __java for XML file operations

Source: Internet
Author: User

First, the directory structure and the functionality within the file are listed:

Com.testxml. Main//entry of all objects, test class
. Books//Entities
. boos.xml//xml File
. Booksdao//Convert the values in the entity into XML files and save them to the XML file in the development directory
Parse XML file into list< entity >
. Testxml//unconformity operations on XML files
. xmlutil//xml Tool class, creating a Document object
Gets the value of the child node of the parent node, only the child node under the parent node is the end element
Writes the document object to the specified XML file

Delete the specified node and its child nodes

XML Tool Class Code:

Package com.testxml;

Import Java.io.File;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import Javax.xml.transform.Result;
Import Javax.xml.transform.Source;
Import Javax.xml.transform.Transformer;
Import Javax.xml.transform.TransformerFactory;
Import Javax.xml.transform.dom.DOMSource;

Import Javax.xml.transform.stream.StreamResult;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;

Import org.w3c.dom.NodeList; public class Xmlutil {/** * Create Document Object * @param relative path * @return * @throws Exception/public static docum ENT getdocument (String str) throws Exception {//Get DOM parser factory documentbuilderfactory DBF = Documentbuilderfactory.newin
		Stance ();
		Gets the specific parser Documentbuilder db = Dbf.newdocumentbuilder ();
		Parse XML file to get Document Object Document document = Db.parse (new file (str));
	return document; /** * Gets the value of the child node of the parent node, only the child node under the parent node is the end element * @param document XML Object * @param parentsrt Parent element * @param childstr child element
	 * @param i the first few parent elements, starting from 0 * @return/public static String Getchildvalue (Document document,string Parentsrt,strin
	    G Childstr,int i) {nodelist list = document.getElementsByTagName (PARENTSRT);
	    element element = (Element) list.item (i);
	    if (element==null) {throw new NullPointerException ("The specified parent node does not exist");
		String content = Element.getelementsbytagname (childstr). Item (0). Getfirstchild (). Getnodevalue ();
	return content; /** * Writes the Document object to the specified XML file * @param document * @param str XML directory * @throws Exception/Public STA tic void savedocument (Document document,string str) throws Exception {transformerfactory transformerfactory = Tran  
        Sformerfactory.newinstance ();  
        STEP10: Obtain a Transformer object Transformer Transformer = Transformerfactory.newtransformer ();  
        STEP11: Wrapping the Document object with a Domsource object Source xmlsource = new Domsource (document); STEP12: Create a Storage target object result OutputtaRget = new Streamresult (new File (str));
        STEP13: Generate the corresponding XML file Transformer.setoutputproperty ("Encoding", "UTF-8");  
	 Transformer.transform (Xmlsource, outputtarget); /** * Deletes the specified node and its child nodes * @param name node key * @param str XML file directory * @return * @throws Exception/P 
		 Ublic Static Boolean Delete (Document document,string name,string str) throws Exception {Boolean result = false; 
		 NodeList nodelists = document.getelementsbytagname (name);
		 int Len=nodelists.getlength (); Iterate through this nodelist, each time the first of the nodelist is deleted, because the size of the nodelist is a constantly changing for (int i=0;i<len;i++) {nodelists.item (0). getparentn 
		 Ode (). RemoveChild (Nodelists.item (0));
		 } xmlutil.savedocument (document, str);
		 Result=true;
	 return result; public static void Main (string[] args) throws Exception {Document document=xmlutil.getdocument ("./src/testxml/boo
		Ks.xml ");
		String Value=xmlutil.getchildvalue (document, "book", "title", 1); System.out.println (value);
	}

}
 


Booksdao Class Code:

Package com.testxml;
Import java.util.ArrayList;

Import java.util.List;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;

Import org.w3c.dom.NodeList;
	public class Booksdao {private document document;
		Public Booksdao (String str) throws Exception {if (document==null) {document = Xmlutil.getdocument (str); /** * Converts the value in an entity to an XML file and saves it to an XML file in the development directory * @param books entity * @param str The path of the XML file @return whether the save succeeded * @th  Rows Exception */public Boolean save (books books,string str) throws Exception {if (books==null) {throw  
		 New IllegalArgumentException ("entity class book cannot be null"); 
		 
		 Boolean result = false; 
		 Element book = document.createelement ("book");  
		 Adds an attribute to the acquired book element Book.setattribute ("category", Books.getcategory ());  
		 Create element, add to book above element title = Document.createelement ("title"); 
		 Title.settextcontent (Books.gettitle ());
		 Book.appendchild (title); Element Author = Document.createelemENT ("author");
		 Author.settextcontent (Books.getauthor ());
		 
		 Book.appendchild (author);
		 Gets the root node, and the root node adds the book element node Tempnode=document.getelementsbytagname ("Booklist"). Item (0);
		 
		 Tempnode.appendchild (book);
		 Xmlutil.savedocument (document, str);
		 Result=true;
	 return result;
	 /** * Deletes the specified node and its child nodes * @param name node key * @param str XML file directory * @return * @throws Exception * *
		 public void Delete (String name,string str) throws Exception {Boolean result=xmlutil.delete (document, name, str); if (result==true) {System.out.println ("delete succeeded.")
		 "); /** * Parse XML file into list< entity > * @param name * @return/public list<books> getentitylist (
		 String name) {list<books> booklists=new arraylist<books> ();
		 NodeList nodelists = document.getelementsbytagname (name); 
             for (int i=0;i<nodelists.getlength (); i++) {Element E = (element) nodelists.item (i); Books books=new BoOKs ();
             Books.setcategory (E.getattribute ("category"));
             Books.settitle (E.getelementsbytagname ("title"). Item (0). Gettextcontent ());
             Books.setauthor (E.getelementsbytagname ("author"). Item (0). Gettextcontent ());
		 Booklists.add (books);
	 return booklists;
 }
	
}

books.xml file

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"?>
<booklist>
	<book category= "This is Category 1" >
		<title> This is the title 1</title>
		<author> This is the author 1</author>
	</book>
	< Book category= "This is the Category 2" >
		<title> This is the title 2</title>
		<author> This is the author 2</author>
	</ book>
	<book category= "This is classified 3" >
		<title> This is the title 3</title>
		<author> This is the author 3</ author>
	</book>
	<book category= "This is the Category 4" >
		<title> This is the title 4</title>
		<author> This is the author 4</author>
	</book>
</booklist>
Other file code slightly.


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.