A complete example of XML operations in Java

Source: Internet
Author: User

A complete example of XML operations in Java-W3C dom

This is an example of using Java W3C dom for XML, including basic operations for querying, adding, modifying, deleting, and saving. A complete description of the entire XML operation process. It is suitable for users who are new to Java XML operations for reference and learning.

Suppose there is an XML file: test1.xml

 

<? XML version = "1.0" encoding = "UTF-8"?>
<Books>
<Book>
<Name> Harry Potter </Name>
<Price> 10 </price>
<Memo> This is a nice book. </Memo>
</Book>
<Book id = "B02">
<Name> Romance of the Three Kingdoms </Name>
<Price> 10 </price>
<Memo> one of the four famous books. </Memo>
</Book>
<Book id = "b03">
<Name> region </Name>
<Price> 6 </price>
<Memo> one of the four famous books. </Memo>
</Book>
<Book id = "b04">
<Name> redhouse </Name>
<Price> 5 </price>
<Memo> one of the four famous books. </Memo>
</Book>
</Books>

 

Below is 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 ();

// --- Create 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 ("a better book. ");
Thebook. appendchild (theelem );
Root. appendchild (thebook );
System. Out. println ("--- create a new book ----");
Output (xmldoc );
// --- Create a new book ----

// --- Make some changes to Harry Potter. ----
// --- Query for Harry Potter ----
Thebook = (element) selectsinglenode ("/books/book [name = ''harry Potter''] ", root );
System. Out. println ("--- query for Harry Potter ----");
Output (thebook );
// --- Modify the price of this book at this time -----
Thebook. getelementsbytagname ("price"). Item (0). settextcontent ("15"); // getelementsbytagname returns nodelist, so keep up with item (0)
System. Out. println ("--- modify the price of this book at this time ----");
Output (thebook );
// --- You also want to add an attribute ID with the value B01 ----
Thebook. setattribute ("ID", "B01 ");
System. Out. println ("--- you also want to add an attribute ID with the value B01 ----");
Output (thebook );
// --- Modify Harry Potter. ----

// --- Delete the book Romance of the Three Kingdoms with the ID attribute ----
Thebook = (element) selectsinglenode ("/books/book [@ ID = ''b02'']", root );
System. Out. println ("--- use the ID attribute to delete the book" Romance of the Three Kingdoms ----");
Output (thebook );
Thebook. getparentnode (). removechild (thebook );
System. Out. println ("--- XML after deletion ----");
Output (xmldoc );

// --- Delete all books whose prices are less than 10 ----
Nodelist somebooks = selectnodes ("/books/book [price <10]", root );
System. Out. println ("--- delete all books with prices less than 10 ---");
System. Out. println ("--- eligible books include" + somebooks. getlength () +. ---");
For (INT I = 0; I <somebooks. getlength (); I ++ )...{
Somebooks. Item (I). getparentnode (). removechild (somebooks. Item (I ));
}
Output (xmldoc );

Savexml ("test10000edited.xml", xmldoc );
} Catch (parserconfigurationexception e )...{
E. printstacktrace ();
} Catch (saxexception e )...{
E. printstacktrace ();
} Catch (ioexception e )...{
E. printstacktrace ();
}
}

Public static void output (node)... {// output the XML string of node to the console
Transformerfactory transfactory = transformerfactory. newinstance ();
Try ...{
Transformer transformer = transfactory. newtransformer ();
Transformer. setoutputproperty ("encoding", "gb2312 ");
Transformer. setoutputproperty ("indent", "yes ");

Domsource source = new domsource ();
Source. setnode (node );
Streamresult result = new streamresult ();
Result. setoutputstream (system. Out );

Transformer. Transform (source, result );
} Catch (transformerconfigurationexception e )...{
E. printstacktrace ();
} Catch (transformerexception e )...{
E. printstacktrace ();
}
}

Public static node selectsinglenode (string Express, object source)... {// find the node and return the first qualified Node
Node result = NULL;
Xpathfactory = xpathfactory. newinstance ();
XPath = xpathfactory. newxpath ();
Try ...{
Result = (node) XPath. Evaluate (Express, source, xpathconstants. node );
} Catch (xpathexpressionexception e )...{
E. printstacktrace ();
}

Return result;
}

Public static nodelist selectnodes (string Express, object source)... {// find a node and return a node set that meets the conditions.
Nodelist result = NULL;
Xpathfactory = xpathfactory. newinstance ();
XPath = xpathfactory. newxpath ();
Try ...{
Result = (nodelist) XPath. Evaluate (Express, source, xpathconstants. nodeset );
} Catch (xpathexpressionexception e )...{
E. printstacktrace ();
}

Return result;
}

Public static void savexml (string filename, document DOC)... {// output document to file
Transformerfactory transfactory = transformerfactory. newinstance ();
Try ...{
Transformer transformer = transfactory. newtransformer ();
Transformer. setoutputproperty ("indent", "yes ");

Domsource source = new domsource ();
Source. setnode (DOC );
Streamresult result = new streamresult ();
Result. setoutputstream (New fileoutputstream (filename ));

Transformer. Transform (source, result );
} Catch (transformerconfigurationexception e )...{
E. printstacktrace ();
} Catch (transformerexception e )...{
E. printstacktrace ();
} Catch (filenotfoundexception e )...{
E. printstacktrace ();
}
}
}

 

Article Source: http://www.diybl.com/course/3_program/java/javashl/200833/102631.html

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.