Building XML With Java And DOM

Introduction

XML is a flexible data formatting structure that can be used to transfer data between applications amongst other things. XML is commonly used by many web technologies to communicate, for example RSS feeds are an example of an XML document. This tutorial will cover how to build and write XML data structures in Java.

Basic XML Format

Documents start with a special tag that specifies the version of XML document and the document encoding format, ex: . All tags start with a < and end with a >, but only the special XML tag needs the ?. Documents are made up of one or more nodes or nested structures of nodes. Each node is represented by a tag in the document.

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <contacts>
        <contact>
            <name>John Doe</name>
            <phone>123-456-7890</phone>
        </contact>
        <contact>
            <name>Bob Smith</name>
            <phone>123-555-1212</phone>
        </contact>
    </contacts>
</root>


Simple Output

Using the output writer and building by hand. This is the simplest way to write simple XML structures. Simply store the XML structure in a string or send directly to the output writer. First building structures by hand will be covered then the tutorial will explain using DOM with Java.

public class SimpleXMLOut {
    public static void main(String args[]) {
        String[] input = {"John Doe,123-456-7890", "Bob Smith,123-555-1212"};
        String[] line = new String[2];

        System.out.println("<?xml version="1.0" encoding="UTF-8"?>");
        System.out.println("<root>");
        System.out.println("    <members>");
        for (int i=0; i < input.length; i++) {
            line = input[i].split(",");
            System.out.println("        <member>");
            System.out.println("            <name>" + line[0] + "</name>");
            System.out.println("            <phone>" + line[1] + "</phone>");
            System.out.println("        </member>");
        }
        System.out.println("    </members>");
        System.out.println("</root>");
    }
}


First initialize a string array to hold the data that will build the XML structure and a second string array to hold the data items contained in the line. Now output the XML header tag, root tag, and members tag. Next loop through the data splitting the line on comma. Build the XML tag member and nest the name and phone tags. The name and phone tags contain the data as text nodes. Close the tags and it's done.

Using DOM

Creating a document is done with the DocumentBuilderFactory and DocumentBuilder classes. The method DocumentBuilder.newDocument is used to create the document. Documents are made up of elements which are the base objects of DOM documents. Use the createElement method of the document object, and pass the name of the element as a parameter.

Once an element has been created it must be appended to the document. Use the appendChild function of the parent element or document object passing the child element as a parameter. To nest elements simply use the appendChild method of the element you wish to be the parent of the node.

import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DOMBasicDoc {
    public static void main(String args[]) {
        try {
            String[] input = {"John Doe,123-456-7890", "Bob Smith,123-555-1212"};
            String[] line = new String[2];
            DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
            DocumentBuilder build = dFact.newDocumentBuilder();
            Document doc = build.newDocument();
            Element root = doc.createElement("root");
            doc.appendChild(root);
            Element memberList = doc.createElement("members");
            root.appendChild(memberList);
            for (int i = 0; i < input.length; i++) {
                line = input[i].split(",");
                Element member = doc.createElement("member");
                memberList.appendChild(member);
                Element name = doc.createElement("name");
                name.appendChild(doc.createTextNode(line[0]));
                member.appendChild(name);
                Element phone = doc.createElement("phone");
                phone.appendChild(doc.createTextNode(line[1]));
                member.appendChild(phone);
            }
            TransformerFactory tFact = TransformerFactory.newInstance();
            Transformer trans = tFact.newTransformer();

            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            System.out.println(writer.toString());

        } catch (TransformerException ex) {
            System.out.println("Error outputting document");
        } catch (ParserConfigurationException ex) {
            System.out.println("Error building document");
        }
    }
}


First setup the string array input containing the data to build the XML structure from. The string array line will be used to hold the split CSV input data. Next initialize the DocumentBuilderFactory object. Use the DocumentBuilderFactory to create a DocumentBuilder instance with the newDocumentBuilder() method. Finally create the document with the DocumentBuilder object using the newDocument() method. This is why for small simple structures strings are quicker and easier, using DOM can be verbose.

Building documents is as simple as creating elements and appending them as children where they should go in the document. First create the root element with the document objects createElement() method passing the name of the element as a parameter. Elements are the tags in the XML document. Next use the appendChild method of the document to append the root tag to the document. Now create an element "members". The list of members will be appended to this element. Use the createElement() method of the document object to create the members element. Now use the root element objects appendChild() method to append the members element as a child of the root tag. Always use the appendChild() method of the parent object to which new node should be nested.

Loop through the input array to build the member list. Each time through the loop set the string array input to the comma split values of the input array data. Create a new element member and append it to the members node. Next create child nodes to hold the name and phone number values from the input array. Use createElement() to create name and phone elements. To store a text value in a tag use the createTextNode() method of the document object. Pass the text value as a parameter to the createTextNode() method. Append the text node to the element that will hold the value. Append the name and phone elements to the member tag created on each iteration of the loop.

Now that the document is built it has to be transformed to be displayed as a string or sent to an output stream. First initialize the TransformerFactory and use newTransformer() to create the transformer object. The transformer object will be used to take the DOM and pass it to the output stream. Next initialize a StringWriter object. Then create a StreamResult object and pass it the StringWriter object.

Build a new DOMSource object from the document. Now use the transformer object to transform the DOM to the output stream. Finally to output the XML use the StringWriters toString() method to get the XML as a string. Both the Transformer and the DOM DocumentBuilder throw exceptions, TransformerException and ParserConfigurationException respectively. For the sake of simplicity this tutorial simply passes them to the built in java logger.




Attributes

Attributes are key value pairs that can be attached to elements. They are stored inside the tag in the document, ex: text node .

import java.io.StringWriter;
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.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DOMAttrDoc {
    public static void main(String args[]) {
        try {
            String[] input = {"John Doe,123-456-7890,123 Fake St,Atlanta,GA,30012", "Bob Smith,123-555-1212,456 Fake St,Atlanta,GA,30012"};
            String[] line = new String[6];

            DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
            DocumentBuilder build = fact.newDocumentBuilder();
            Document doc = build.newDocument();
            Element root = doc.createElement("root");
            doc.appendChild(root);
            Element memberList = doc.createElement("members");
            root.appendChild(memberList);
            for (int i = 0; i < input.length; i++) {
                line = input[i].split(",");
                Element member = doc.createElement("member");
                member.setAttribute("name", line[0]);
                member.setAttribute("phone", line[1]);
                member.setAttribute("street", line[2]);
                member.setAttribute("city", line[3]);
                member.setAttribute("state", line[4]);
                member.setAttribute("zip", line[5]);
                memberList.appendChild(member);
            }
            TransformerFactory tFact = TransformerFactory.newInstance();
            Transformer trans = tFact.newTransformer();
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            System.out.println(writer.toString());

        } catch (TransformerException ex) {
            System.out.println("Error outputting document");
        } catch (ParserConfigurationException ex) {
            System.out.println("Error building document");
        }
    }
}


As before initialize the data set and the array to hold the comma split values. Notice the extra fields in the data from the previous example. Setup the DocumentBuilderFactory and DocumentBuilder objects to create the document. Now create the root element and attach it to the document. As before create the root tag with the createElement() method and use appendChild() to attach it to the document. Use the createElement() method to create the members tag that the list will be the parent of the member elements and append it to the root node. The values of the input array will be stored in the XML document as attributes of the member node.

Loop through the values of the array. First split the array value into comma seperated values with split. Next create the member node. Use the setAttribute() method of the member node object to add the values to the node. The setAttribute() method expects the attribute name and value to be passed as parameters. Once all the attributes are added append the member node as a child of the members node.

When the loop completes the TransformerFactory is used to convert the DOM document to a string. Use the TransformerFactory object to create a Transformer object. To build a document that is easier for humans to read use the setOutputProperty() method of the transformer object to set the OutputKeys.INDENT value to yes. This will insert tabs and line feeds into the document.

Build a StringWriter and StreamResult to pass to the transformer to get the XML as a string. Initialize a DOMSource object for the transformer to use to get the XML from the DOM object. The transformer objects transform method is used to convert the DOM object to a string. Use the StringWriters toString method to get the text value of the XML. The last thing to do is catch the possible exceptions that might be thrown. The ParserConfigurationException is thrown by the DocumentBuilder and the TransformerException is thrown by the Transformer object



[출처] http://www.higherpass.com/java/Tutorials/Building-Xml-With-Java-And-Dom/1/



경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
50 SWT JAVA 동적으로 컨트롤을 추가하는 다이얼로그 졸리운_곰 2015.04.27 455
49 swt java xulrunner 3.6 캐쉬 비우기 : html 깨짐 졸리운_곰 2015.04.27 339
48 A simple Java console: 졸리운_곰 2015.04.24 312
47 XML Processing using XERCES Java Parser file 졸리운_곰 2015.04.22 409
46 SWT – MouseListener & MouseAdapter Example 졸리운_곰 2015.04.22 297
45 JAVA SWT XULRUNNER 브라우저 target=_black 멀티 윈도우 표시 졸리운_곰 2015.04.20 401
44 ClassNotFoundException in handlers and Viewparts eclipse rcp e4 file 졸리운_곰 2015.04.17 309
43 Displaying the console in your RCP application file 졸리운_곰 2015.04.17 390
42 Eclipse RCP 프로그램에서 Console 뷰 사용하기 file 졸리운_곰 2015.04.17 526
41 SolrJ Tutorial 졸리운_곰 2015.04.08 332
40 Introduction to XML and XML With Java 졸리운_곰 2015.03.31 327
39 Java SWT 소개 file 졸리운_곰 2015.03.30 358
38 Getting Controls on a shell : Shell « SWT « Java Tutorial file 졸리운_곰 2015.03.30 229
37 Introduction to XML and XML With Java 졸리운_곰 2015.03.19 329
» Building XML With Java And DOM 졸리운_곰 2015.03.19 337
35 XML file to Treeviewer file 졸리운_곰 2015.03.19 399
34 Java로 외부 프로그램 실행 ( ProcessBuilder 사용) 졸리운_곰 2015.03.17 1175
33 Java Clipboard 자바 클립보드 복사/붙여넣기 졸리운_곰 2015.03.17 2214
32 Java GUI(AWT) 프로그래밍 file 졸리운_곰 2015.03.09 938
31 자바로 디스크에 저장된 파일 읽기 졸리운_곰 2015.03.09 609
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED