JAXP manipulating XML

Source: Internet
Author: User

Dom object in a detailed
1. Basic DOM Objects

There are 5 basic objects for DOM: Document,node,nodelist,element and attr. Here is a general introduction to the functions of these objects and how they are implemented.

The Document object represents the entire XML documentation, and all other node, in a certain order, is contained within the document object, arranged into a tree structure, where the programmer can traverse the tree to get all the contents of the XML document, which is also the starting point for the operation of the XML document. We always first get a Document object by parsing the XML source file and then perform the subsequent operations. In addition, document also contains methods for creating other nodes, such as createattribut () to create a attr object. The main methods it contains are:

CreateAttribute (String): Creates a attr object with the given property name, and can then be placed above an element object using the Setattributenode method.

CreateElement (String): Creates an element object with the given tag name, represents a label in the XML document, and can then add attributes to or perform other operations on the element object.

createTextNode (String): Creates a text object with the given string that represents the plain text string contained in the label or property. If there is no other label within a tag, the text in the label represents the object that is the only child of the element object.

getElementsByTagName (String): Returns a NodeList object that contains all labels for the given tag name.

Getdocumentelement (): Returns an Element object representing the root node of the DOM tree, which is the object representing the root element of the XML document.

The node object is the most basic object in the DOM structure and represents an abstract node in the document tree. In practice, it is very rare to actually use node as the object, but to manipulate the document using sub-objects such as Element, Attr, text, and so on. The node object provides an abstract, public root for these objects. Although the method of accessing the child nodes is defined in the node object, it is important to note that there are some node sub-objects, such as text objects, that do not have child nodes. The main methods that the Node object contains are:

AppendChild (Org.w3c.dom.Node): Add a child node for this node and place it at the end of all child nodes, and if the child node already exists, delete it and add it first.

Getfirstchild (): If a node has child nodes, it returns the first child node, the peer, and the Getlastchild () method to return the last child node.

Getnextsibling (): Returns the next sibling node of this node in the DOM tree, the peer, and the Getprevioussibling () method to return to its previous sibling node.

Getnodename (): Returns the name of the node based on the type of the node.

Getnodetype (): Returns the type of the node.

Getnodevalue (): Returns the value of the node.

HasChildNodes (): Determines whether there are child nodes.

HasAttributes (): Determines whether the node exists with attributes.

Getownerdocument (): Returns the Document object where the node is located.

InsertBefore (Org.w3c.dom.Node new,org.w3c.dom.node ref): Inserts a sub-object before a given sub-object.

RemoveChild (Org.w3c.dom.Node): Deletes the given child node object.

ReplaceChild (Org.w3c.dom.Node new,org.w3c.dom.node old): Replaces the given child node object with a new node object.

The NodeList object, as the name implies, represents a list that contains one or more node. You can simply think of it as an array of node, and we can get the elements in the list by means of a method:

GetLength (): Returns the length of the list.

Item (int): Returns the Node object at the specified location.

The element object represents the tag elements in an XML document, which is inherited from node, and is also the primary child object of node. You can include attributes in a tag, so the element object has methods to access its properties, and any method defined in node can also be used on the element object.

getElementsByTagName (String): Returns a NodeList object that contains a label with the name of the given tag in the descendant node under the tag.

Gettagname (): Returns a String representing the name of the tag.

GetAttribute (String): Returns the value of the property for the given property name in the label. The main requirement here is that entity attributes should be allowed in the XML document, and this method does not apply to these entity attributes. The Getattributenodes () method is needed to get a attr object for further operation.

GetAttributeNode (String): Returns a Attr object that represents the name of the given property.

The Attr object represents a property in a tag. Attr inherits from node, but because attr is actually contained in element, it cannot be considered as a sub-object of element, so attr in the DOM is not part of the DOM tree, so Getparentnode () in node, Both getdivvioussibling () and getnextsibling () will return null. In other words, attr is actually considered part of the element object that contains it, and it does not appear as a separate node in the DOM tree. This is different from other node sub-objects when used.

It should be noted that the above mentioned DOM object is defined in the DOM by the interface, and Dom can actually be implemented in any object-oriented language, as long as it implements the interfaces and functions defined by the DOM.

2, about JAXP bag

The JAXP Development Kit is part of the J2SE, which consists of Javax.xml, Org.w3c.dom, org.xml.sax packages and their child packages

In the Javax.xml.parsers package, several factory classes are defined, and the programmer calls these factory classes to get the parser object for the DOM or SAX parsing the XML document.

Using JAXP for DOM parsing

The documentbuilderfactory used in the Javax.xml.parsers package to create the parser object for the DOM pattern, Documentbuilderfactory is an abstract factory class that cannot be instantiated directly, However, this class provides a Newinstance method that automatically creates a factory object and returns based on the parser installed by default on the local platform.

Get the DOM parser in JAXP

Call the Documentbuilderfactory.newinstance () method to get the factory that created the DOM parser.

Invokes the Newdocumentbuilder method of the factory object to get the DOM parser object.

Invoking the Parse () method of the DOM parser object parses the XML document and obtains the Document object representing the entire file, which can be manipulated using the DOM attribute for the entire XML document.

Updating an XML document

The transformer class in the Javax.xml.transform package is used to output the Document object that represents the XML file to a certain format, such as converting an XML file into an HTML document after applying a stylesheet. Using this object, it is also possible to write the document object back into an XML file.

The transformer class completes the conversion operation through the transform method, which receives a source and a destination. We can do this by:

The Javax.xml.transform.dom.domsource class to associate the Document object to be converted,

• Use the Javax.xml.transform.stream.StreamResult object to represent the destination of the data.

The transformer object is obtained through transformerfactory.

See a simple example:

Book.xml

<?xmlversion="1.0"encoding="UTF-8"standalone="No"?>

<book>

<bookname>java Programming </bookname>

<bookprice>40 Yuan </bookprice>

<author>lijizh</author>

<publisher>lijizh1013</publisher>

</book>

Dom.java

Package DTD;

Import java.io.IOException;

Import Javax.xml.parsers.DocumentBuilder;

Import Javax.xml.parsers.DocumentBuilderFactory;

Importjavax.xml.parsers.ParserConfigurationException;

Import org.w3c.dom.Document;

Import Org.w3c.dom.Node;

Import org.w3c.dom.NodeList;

Import org.xml.sax.SAXException;

Publicclass Dom {

Publicstaticvoid Main (string[] args) throws Parserconfigurationexception,saxexception, IOException {

Get the Resolution factory

Documentbuilderfactory dbf = documentbuilderfactory. newinstance ();

Creating a Parser Object

Documentbuilder db = Dbf.newdocumentbuilder ();

Get Document Object

Document d = db.parse ("Src/dtd/book.xml");

Get the appropriate node list by using the Document object's method

NodeList nl = d.getelementsbytagname ("BookName");

Gets the specified node

Node node = nl.item (0);

Gets the contents of the specified node

String content = Node.gettextcontent ();

Output content

System. out. println (content);

}

}

Example to complete a crud operation on an XML file:

Book.xml

<?xmlversion="1.0"encoding="UTF-8"standalone="No"?>

<book>

<bookname>java Programming </bookname>

<bookprice>40 Yuan </bookprice>

<author>lijizh</author>

<publisher>lijizh1013</publisher>

</book>

Readdom.java

Package DTD;

Import java.io.IOException;

Import Javax.xml.parsers.DocumentBuilder;

Import Javax.xml.parsers.DocumentBuilderFactory;

Importjavax.xml.parsers.ParserConfigurationException;

Import Javax.xml.transform.Transformer;

Import javax.xml.transform.TransformerConfigurationException;

Importjavax.xml.transform.TransformerException;

Importjavax.xml.transform.TransformerFactory;

Import Javax.xml.transform.dom.DOMSource;

Importjavax.xml.transform.stream.StreamResult;

Import Org.junit.Test;

Import org.w3c.dom.Document;

Import org.w3c.dom.Element;

Import Org.w3c.dom.Node;

Import org.w3c.dom.NodeList;

Import org.xml.sax.SAXException;

Publicclass Readdom {

@Test

Publicvoid read () throws Parserconfigurationexception, Saxexception, ioexception{

Documentbuilderfactoryfactory = Documentbuilderfactory. newinstance ();

Documentbuilder db =factory.newdocumentbuilder ();

Document d = db.parse ("Src/dtd/book.xml");

Node node = d.getelementsbytagname ("book"). Item (0);

System.out.println (Node.getnodename ());

List (node);

}

Use this method to traverse element nodes

Privatevoid List (node node) {

if (node instanceof Element)

{

System. out. println (Node.getnodename ());

}

NodeList list = Node.getchildnodes ();

for (int i = 0;i< list.getlength (); i++) {

Node Node1 =list.item (i);

List (Node1);

}

}

@Test

method of adding data to an XML file in the form of a trailing append

Publicvoid Insert () throws Parserconfigurationexception, Saxexception,ioexception, transformerexception{

Documentbuilderfactory Factory =documentbuilderfactory. newinstance ();

Documentbuilderdb = Factory.newdocumentbuilder ();

Document d = db.parse ("Src/dtd/book.xml");

element node = (element) d.getelementsbytagname ("book"). Item (0);

Element newNode =d.createelement ("color");

Newnode.settextcontent ("Red");

Node.appendchild (NewNode);

Obtain a factory instance by converting the factory's Newinstance () method

Transformerfactory TFF =transformerfactory. newinstance ();

Get converter

Transformer TF =tff.newtransformer ();

Connecting the source to the destination file via the transform method of the converter object

Tf.transform (New Domsource (d), New Streamresult ("Src/dtd/book.xml"));

}

@Test

Ways to add data to an XML file in a forward-inserted way

Publicvoid Insert1 () throws Parserconfigurationexception, Saxexception, ioexception,transformerexception{

Documentbuilderfactory factory = documentbuilderfactory. newinstance ();

Documentbuilder db = Factory.newdocumentbuilder ();

Document d = db.parse ("Src/dtd/book.xml");

element node = (element) d.getelementsbytagname ("book"). Item (0);

Element NewNode = d.createelement ("publisher");

Newnode.settextcontent ("Lijizh");

Element refchild = (Element) d.getelementsbytagname ("Color"). Item (0);

Node.insertbefore (NewNode, refchild);

Transformerfactory TFF = transformerfactory. newinstance ();

Transformer tf = Tff.newtransformer ();

Tf.transform (New Domsource (d), New Streamresult ("Src/dtd/book.xml"));

}

@Test

Ways to delete data from an XML file

Publicvoid Delete () throws Parserconfigurationexception, Saxexception, ioexception,transformerexception{

Documentbuilderfactory factory = documentbuilderfactory. newinstance ();

Documentbuilder db = Factory.newdocumentbuilder ();

Document d = db.parse ("Src/dtd/book.xml");

element node = (element) d.getelementsbytagname ("Color"). Item (0);

Element parent = (Element) Node.getparentnode ();

Parent.removechild (node);

Transformerfactory TFF = transformerfactory. newinstance ();

Transformer tf = Tff.newtransformer ();

Tf.transform (New Domsource (d), New Streamresult ("Src/dtd/book.xml"));

}

@Test

Ways to update data from an XML file

Publicvoid update () throws Parserconfigurationexception, Saxexception, ioexception,transformerexception{

Documentbuilderfactory factory = documentbuilderfactory. newinstance ();

Documentbuilder db = Factory.newdocumentbuilder ();

Document d = db.parse ("Src/dtd/book.xml");

element node = (element) D.getelementsbytagname ("publisher"). Item (0);

Node.settextcontent ("lijizh1013");

Transformerfactory TFF = transformerfactory. newinstance ();

Transformer tf = Tff.newtransformer ();

Tf.transform (New Domsource (d), New Streamresult ("Src/dtd/book.xml"));

}

}

}

JAXP manipulating XML

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.