Dom parsing and XML generation in Sun's JAXP Parsing

Source: Internet
Author: User

Although Sun's XML parsing performance is not the best, it is convenient and does not need to import third-party packages.

<?xml version="1.0" standalone="yes"?><Root>  <VID>2012/2/20 15:33:36</VID>  <Mac>000B6CCCAE2C</Mac>  <ServerIP>191.255.1.102</ServerIP>  <ServerPort>3130</ServerPort>  <PassWord>111111</PassWord>  <System>Android2.3</System></Root>

Dom parsing has three important classes: Document, element, and node.

Docuement represents the entire XML file.

Element represents an element. For example, <vid> 15:33:36 </vid> is an element. <Root> to </root> is also an element.

A node represents a node. A node is an object wrapped in <>. For example, <root> is a node. Note that node is a super interface, and both docuement and element are subclasses of node.

After understanding what the above three classes represent, it is easy to parse.

Create a DOM parser and parse the XML file to obtain the document object. The parsed object can be a stream, file, or file path.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();Document d = db.parse(PATH);

 

The following describes some methods that may be used for parsing.

Document

Nodelist getelementsbytagname (string tagname) obtains all nodes with this label based on the tag name. (Subnode under the first node)

Element getdocumentelement () gets the first element. For example, the XML above will get the element object representing <root>.

Element

String gettagname () obtains the tag name, that is, the name contained in <>, which is the same as the getnodename result inherited from node.

Nodelist getelementsbytagname (string name) obtains the nodes with the label name for all the child elements of this element based on the tag name. (Subnodes under Element nodes)

String getattribute (string name) Get the attribute value through the attribute name

Nodelist

Int getlength () node count

Node item (INT index) returns the node at the specified position

Node

Node getparentnode () to get the parent node

Node getfirstchild () obtains the first subnode of the node.

Node getlastchild () obtains the last subnode of the connected node.

String getnodename () to get the node name

Document getownerdocument () obtains the entire document object related to the node.

Node getnextsibling () to get the next node. (Note: The final node is obtained, and the obtained nodes are all nodes in the same depth and are not subnodes)

Node getpreviussibling () gets the previous node. It may be null like the preceding method. (The End node uses the getnodename method to obtain the node type instead of the node label)

Namednodemap getattributes () obtains the names and values of all attributes of the node, which are stored in the namednodemap object.

String gettextcontent () obtains the text value in the middle of the node, which is the data we need.

To understand Dom parsing, write it in comparison to the above method!

Dom-based XML file generation

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();Document d =db.newDocument();

If it is not to generate a new XML file, but to modify the original XML file, the above method for getting the Document Object is changed to the method for parsing.

Methods required to generate or modify XML files

Document)

Element createelement (string tagname) creates a new element

String getxmlencoding () obtains the encoding type.

Boolean getxmlstandalone () is an independent document

String getxmlversion () to get the version Declaration

Void setxmlstandalone (Boolean xmlstandalone) (if it is false, standalone = "no" is displayed, and true is not displayed)

Void setxmlversion (string xmlversion) is a single version. The default value is also 1.0.

Element)

Boolean hasattributes () has attributes

Void setattribute (string name, string value) adds an attribute to the element.

Void removeattribute (string name) removes an attribute by name. If it is read-onlyDomexception exception

Node)

Node appendchild (node newchild) mounts a new node to this node as a subnode of this node.

Void settextcontent (string textcontent) sets the text content after this node.

Node replaceChild (node newchild, node oldchild) replaces the oldchild in the child node with the newchild node.

Node removechild (node oldchild) removes the oldchild subnode of this node.

Boolean haschildnodes () indicates whether a subnode exists.

All the nodes mentioned above refer to the label node. The label node actually has a subnode, that is, the text node, but it does not seem to be used for XML.

Text

String getwholetext () to get the entire text content. The result is generally equivalent to the gettextcontent () of node.
Text
All texts of a node (logically adjacent to this node) in string in document order

Text replacewholetext (string content) replaces the text of the current node and all logically adjacent text nodes with the specified text (not tested)

Text splittext (INT offset) in the specifiedoffsetSplit the node into two nodes and keep them in the tree as brother nodes (not tested)

After you write (modify) the required XML file, you need to save it as a file to the storage device.

public static void saveMyDocument(Node node) throws TransformerException{TransformerFactory tf = TransformerFactory.newInstance();Transformer t = tf.newTransformer();t.setOutputProperty(OutputKeys.INDENT, "yes");Result r =  new StreamResult(new File("E:/aaa.xml"));t.transform(new DOMSource(node), r);}
Transformer 

Void transform (source xmlsource, result outputtarget) converts the implementation Class Object of the source interface to the implementation Class Object of the result interface.

Void setoutputproperty (string name, string value) is used to set the parameters for conversion. The keys of the parameters refer to fields in the outputkeys class.

Outputkeys

String encoding Encoding

Whether the string indent is in beautiful format. The default format is compact. The beautiful Format refers to the above XML format. Optional values: "yes" and "no"

The source interface is generally implemented using domsource. The ConstructorDOMSource(Node n)

The result interface is generally implemented using streamresult. The constructor methods include streamresult (file F), streamresult (outputstream), and streamresult (writer)

The method for generating the above XML file is as follows:

public void createXml() throws ParserConfigurationException, TransformerException{DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();Document d =db.newDocument();d.setXmlVersion("1.0");d.setXmlStandalone(true);Element root = d.createElement("Root");d.appendChild(root);Element e = d.createElement("VID");e.setTextContent("2012/2/20 15:33:36");root.appendChild(e);e = d.createElement("Mac");e.setTextContent("000B6CCCAE2C");root.appendChild(e);e = d.createElement("ServerIP");e.setTextContent("191.255.1.102");root.appendChild(e);e = d.createElement("ServerPort");e.setTextContent("3130");root.appendChild(e);e = d.createElement("PassWord");e.setTextContent("111111");root.appendChild(e);e = d.createElement("System");e.setTextContent("Android2.3");root.appendChild(e);DoXml.saveMyDocument(d);}

The savemydocument method in the above method is as follows:

public static void saveMyDocument(Node node) throws TransformerException{TransformerFactory tf = TransformerFactory.newInstance();Transformer t = tf.newTransformer();t.setOutputProperty(OutputKeys.INDENT, "yes");Result r =  new StreamResult(new File("E:/aaa.xml"));t.transform(new DOMSource(node), r);}

Disadvantages:

1. When obtaining an attribute, you must know the attribute name to obtain the attribute value. Instead, you cannot directly obtain all attribute names and values.

2. only the getchildnodes method that obtains all the nodes under the node (including the subnodes of the subnode) is used to obtain all the subnodes, there is no method for obtaining only the subnode of this node (excluding the subnode of the subnode ).

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.