Using the XML parsing development package JAXP to perform a DOM-style crud operation on an XML file

Source: Internet
Author: User

It Programmer development Essentials-all kinds of resources download list, history of the most IT resources, personal collection summary. package EDU.JAXP;

Import java.io.FileNotFoundException;

Import Java.io.FileOutputStream;

Import Javax.xml.parsers.DocumentBuilder;

Import Javax.xml.parsers.DocumentBuilderFactory;

Import Javax.xml.transform.Transformer;

Import javax.xml.transform.TransformerConfigurationException;

Import javax.xml.transform.TransformerException;

Import Javax.xml.transform.TransformerFactory;

Import Javax.xml.transform.dom.DOMSource;

Import Javax.xml.transform.stream.StreamResult;

Import Org.junit.Test;

Import org.w3c.dom.Document;

Import org.w3c.dom.Element;

/**

* Test CRUD Operations on document objects

**/

public class Jaxpdomcrud {

Parse the XML document and get the document that represents it

Public Document GetDocument () {

Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();

Documentbuilder builder = null;

Document document = NULL;

try {

Builder = Factory.newdocumentbuilder ();

Document = Builder.parse ("Webroot/product1.xml");

} catch (Exception e) {

TODO auto-generated Catch block

E.printstacktrace ();

}

return document;

}

Update the in-memory modified document object to an XML document

public void Updatexml (Document documentsrc) {

Get Transformerfactory Instance Object

Transformerfactory transformerfactory = Transformerfactory.newinstance ();

Creating transformer objects from Transformerfactory objects

Transformer Transformer = null;

try {

Transformer = Transformerfactory.newtransformer ();

} catch (Transformerconfigurationexception E1) {

TODO auto-generated Catch block

E1.printstacktrace ();

}

/*

* Call the transform (Source xmlsource, Result outputtarget) method of the Transformer object

* Public class Domsource extends Object implements Source

* Construction Method: Domsource (Node N)

* Public class Streamresult extends Object implements Result

* Construction Method: Streamresult (OutputStream outputstream)

*/

try {

Transformer.transform (New Domsource (DOCUMENTSRC),

New Streamresult (New FileOutputStream ("Webroot/product1.xml"));

} catch (FileNotFoundException e) {

TODO auto-generated Catch block

E.printstacktrace ();

} catch (Transformerexception e) {

TODO auto-generated Catch block

E.printstacktrace ();

}

}

Add nodes to <product category= table > Nodes <notes> This is a table and chair </notes>

@Test

public void Appendnode () {

Get the Document object for the XML documents

Document document = GetDocument ();

Create <notes> new node

Element notes = document.createelement ("notes");

Notes.setattribute ("name", "Xiao Hua");

Notes.settextcontent ("This is the table and Chair");

Append a new node created to the second <product> node

Element product = (Element) document.getElementsByTagName ("Product"). Item (1);

Product.appendchild (Notes);

Updating an XML document

Updatexml (document);

}

Adds a node to the specified location in an XML document:<notes> This is a table </notes> chairs

@Test

public void Insertnode () {

Get the Document object for the XML documents

Document document = GetDocument ();

Create <notes> new node

Element notes = document.createelement ("notes");

Notes.setattribute ("name", "Xiao Hua");

Notes.settextcontent ("This is the table and Chair");

Get reference node

Element Refnode = (Element) document.getelementsbytagname ("Price"). Item (1);

Insert the new node you created under the Second <product> node sub-node <price> front

Element product = (Element) document.getElementsByTagName ("Product"). Item (1);

Product.insertbefore (notes, Refnode);

Updating an XML document

Updatexml (document);

}

To specify a node for an XML document to add or modify or delete properties

@Test

public void Setorupdateattr () {

Get the Document object for the XML documents

Document document = GetDocument ();

For <notes> This is the Wrench </notes> node Add property

Element Notesnode = (Element) document.getElementsByTagName ("notes"). Item (0);

Notesnode.setattribute ("name", "Cao Huan");

For <price street= "Macau Street" wholesale= "section" >100.0</price> Modify attribute values

Element Pricenode = (Element) document.getelementsbytagname ("Price"). Item (1);

Pricenode.setattribute ("wholesale", "small");

Remove <specifications weight= "2.0kg" > Wrench </specifications> Weight Properties

Element Specificationsnode = (Element) document.getElementsByTagName ("Specifications"). Item (0);

Specificationsnode.removeattribute ("Weight");

Updating an XML document

Updatexml (document);

}

Delete the specified node in the XML document <notes name= "Cao Huan" > This is a wrench </notes>

@Test

public void Deletenode () {

Get the Document object for the XML documents

Document document = GetDocument ();

Get the node you want to delete

Element Notesnode = (Element) document.getElementsByTagName ("notes"). Item (0);

Gets the parent node of the node to be deleted, and throws a nullpointerexception if the Notenode node is null

Element parentnode = (Element) Notesnode.getparentnode ();

Element parentnode = (Element) document.getElementsByTagName ("Product"). Item (1);

Child nodes removed by parent node

Parentnode.removechild (Notesnode);

Updating an XML document

Updatexml (document);

}

Modifying the contents of element elements

@Test

public void Updatecontexttext () {

Get the Document object for the XML documents

Document document = GetDocument ();

Pricenode can only be a child node of a Productnode node

Element Productnode = (Element) document.getElementsByTagName ("Product"). Item (0);

Element Pricenode = (Element) productnode.getelementsbytagname ("Price"). Item (0);

Pricenode.settextcontent ("90.0");

Updating an XML document

Updatexml (document);

}

}

Product1.xml File Contents:

<?xml version= "1.0" encoding= "Utf-8" standalone= "no"?>

<catalog id= "Cata1" >

<product category= "Handtool" >

<specifications> Wrench </specifications>

<price street= "Hong Kong Street" >90.0</price>

</product>

<product category= "Table" >

<specifications> Tables </specifications>

<notes name= "Xiao Hua" > This is the table and chairs </notes>

<price street= "Macau Street" wholesale= "small" >100.0</price>

</product>

</catalog>



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.