Java--dom Way to generate XML

Source: Internet
Author: User

http://blog.csdn.net/u012325167/article/details/50943202

There are several steps to generating an XML file using the DOM method:

The first is to create the DOM tree (that is, to specify the content in the XML file):

    • Create a Documentbuilderfactory object
    • Creating Documentbuilder objects from Documentbuilderfactory objects
    • Creates a document object from the NewDocument () method of the Documentbuilder object that represents an XML file
    • Creating a root node through the createelement () method of the Document object
    • Create N child nodes by using the createelement () method of the Document object, assign them a value, and add the child nodes to the root node
    • To add a root node under the Document object

The second is to convert the DOM tree to an XML file:

    • To create an object of the Transformerfactory class
    • Creating transformer objects from Transformerfactory
    • Use the transform () method of the Transformer object to convert the DOM tree to an XML file. (The method has two parameters, the first parameter is the source data, you need to create a Domsource object and load the document into it, the second parameter is the destination file, which is the XML file to be generated, you need to create the Streamresult object and specify the destination file)

The following starts:

The first is to create a section of the DOM tree:

To create an object of the Documentbuilderfactory class:

// 创建DocumentBuilderFactoryDocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    • 1
    • 2
    • 1
    • 2

To create a Documentbuilder object:

// 创建DocumentBuilderDocumentBuilder builder = factory.newDocumentBuilder();
    • 1
    • 2
    • 1
    • 2

Create Document:

// 创建DocumentDocument document = builder.newDocument();
    • 1
    • 2
    • 1
    • 2

To create the root node:

// 创建根节点Element bookstore = document.createElement("bookstore");
    • 1
    • 2
    • 1
    • 2

Create child nodes and add properties:
You can create a node by using the document createElement() method, and setAttribute() you can set properties by using the element method.

// 创建子节点,并设置属性Element book = document.createElement("book");book.setAttribute("id", "1");
    • 1
    • 2
    • 3
    • 1
    • 2
    • 3

To add a child node to the book node:
The element can be used to setTextContent() set the content between nodes (the value of the node), and the element appendChild() can be used to add child nodes to the node.

Add a child node to book element name = document. createelement ("Name"); name.settextcontent ( "Andersen fairy tale") .appendchild (name) .createelement ( "author") ;author.settextcontent (;book.appendchild (author) ; Element Price = Document.createelement ( "price") ;p rice.settextcontent ( "49") Span class= "hljs-comment" >;book.appendchild (price)    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

To add a child node to the root node:

// 为根节点添加子节点bookstore.appendChild(book);
    • 1
    • 2
    • 1
    • 2

To add the root node under document:

// 将根节点添加到Document下document.appendChild(bookstore);
    • 1
    • 2
    • 1
    • 2

At this point, the DOM tree is finished.

The following begins the generation of the XML file:

To create a Transformerfactory object:

// 创建TransformerFactory对象TransformerFactory tff = TransformerFactory.newInstance();
    • 1
    • 2
    • 1
    • 2

To create a Transformer object:

// 创建Transformer对象Transformer tf = tff.newTransformer();
    • 1
    • 2
    • 1
    • 2

Use the Transformer object transform() method to convert the DOM tree to XML:

// 使用Transformer的transform()方法将DOM树转换成XMLtf.transform(new DOMSource(document), new StreamResult(dest));
    • 1
    • 2
    • 1
    • 2

This completes the creation of the XML file.

The results of the operation are as follows:

<?xml version= "1.0" encoding= "UTF-8" standalone= "no "? ><bookstore><book id=" 1 "><< Span class= "Hljs-title" >name> Anderson fairy tale </name> <author> Anderson </ author><price>49 </price></ book></BOOKSTORE>   
    • 1
    • 1

The visible XML file was generated successfully. However, the contents of the file are a whole line, not line-wrapping, difficult to read.
At this point, we need to setOutputProperty() set the output properties using the Transformer method, which is set to line break.

// 设置输出数据时换行tf.setOutputProperty(OutputKeys.INDENT, "yes");
    • 1
    • 2
    • 1
    • 2

Run again, the contents of the visible XML file are wrapped correctly:

<?xml version= "1.0" encoding= "UTF-8" standalone= "no "? ><bookstore><book id=" 1 "><< Span class= "Hljs-title" >name> Anderson fairy tale </name> <author> Anderson </ author><price>49 </price></ book></BOOKSTORE>   
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

In addition, you can see that in the Declarations section of the XML file, there is an standalone attribute that represents whether the current XML has a corresponding DTD or schema file as its description document.

If the property value is "Yes", the current XML file does not have a DTD and schema file as its description document.

Since we don't have a DTD and schema here, we can hide the property by using the document setXmlStandalone() method.

// 设置XML声明中standalone为yes,即没有dtd和schema作为该XML的说明文档,且不显示该属性document.setXmlStandalone(true);
    • 1
    • 2
    • 1
    • 2

Once again, you can see that the attribute is not already in the test.

The complete code is given below:

Package util; Import Java, I-. File; Import Javax. xml. parsers. Documentbuilder; Import Javax. xml. parsers. Documentbuilderfactory; Import Javax. xml. parsers. Parserconfigurationexception; Import Javax. xml. Transform. Outputkeys; 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. the. Dom. Document; Import org. the. Dom. Element;p Ublic class Fileutil {public void Createxmlbydom (File dest) {//create documentbuilderfactory documentbuilderfactory factor y = documentbuilderfactory. newinstance (); try {//create Documentbuilder documentbuilder builder = Factory. Newdocumentbuilder (); Create Document Document document = Builder. NewDocument (); The standalone in the set XML declaration is yes, that is, there is no DTD and schema as the description document for the XML, and the attribute/document is not displayed. Setxmlstandalone (True); Create root node Element bookstore = document. createelement ("Bookstore"); Create a child node and set the property Element book = document. createelement ("Book"); Book. SetAttribute ("id","1"); Add a child node to book Element name = document. createelement ("Name"); Name. Settextcontent ("Andersen fairy tale"); Book. appendchild (name); Element Author = document. createelement ("Author"); Author. Settextcontent ("Anderson"); Book. AppendChild (author); Element Price = document. createelement ("Price"); Price. Settextcontent ("49"); Book. appendchild (Price); Add child nodes to the root node bookstore. appendchild (book); Add root node to document. appendchild (Bookstore);/* * Start implementation below: Generate XML File *//Create Transformerfactory object Transformerfactory TFF = transformerfactory. newinstance (); Create Transformer object Transformer tf = TFF. Newtransformer ();///Set output data with a newline TF. Setoutputproperty (Outputkeys. INDENT, "yes");//Use the transformer transform () method to convert the DOM tree to an XML tf. Transform (new Domsource (document), new Streamresult (dest)),} catch (Parserconfigurationexception e) {e. Printstacktrace ();} catch ( Transformerconfigurationexception e) {//TODO auto-generated catch block E.Printstacktrace ();} catch (TRANSFO Rmerexception e) {//TODO auto-generated catch block E.Printstacktrace ();     }} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21st
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21st
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88

Java--dom way to generate XML (GO)

Related Article

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.