Java에서 DOM 파서를 사용하여 XML 파일을 만드는 방법은 무엇입니까? DOM을 XML 파일로 작성하기
게시 됨: 2019-01-11
앞에서 "Java에서 XML 요소 수를 계산하는 간단한 방법"을 배웠듯이 여기에 XML 파일을 Java(DOM Parser)로 작성하는 또 다른 간단한 Java 코드가 있습니다.
- DOM을 XML 파일로 작성하기
- Java DOM 튜토리얼 – Java에서 DOM을 사용하여 XML 작성
- Java에서 XML 파일을 작성하는 방법(DOM 파서)
- Java: Java로 XML(DOM) 파일을 작성하는 간단한 방법
이것이 내가 여기서 하는 일입니다:
- 이름이
Companies
인 루트 XML 요소 생성 - 4개의
Company
요소 생성 - 모든 회사 요소에는 속성
id
가 있습니다. - 모든 회사 요소에는
Name, Type, Employee
3가지 요소가 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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 |
package crunchify . com . tutorials ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . transform . OutputKeys ; import javax . xml . transform . Transformer ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . stream . StreamResult ; /** * @author Crunchify.com * In Java How to Create XML File using DOM parser? Writing Out a DOM as an XML File. * Version: 1.1 */ public class CrunchifyCreateXMLDOM { public static void main ( String [ ] args ) { // Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents. DocumentBuilderFactory crunchifyDocBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; // Defines the API to obtain DOM Document instances from an XML document. DocumentBuilder crunchifyDocBuilder ; try { crunchifyDocBuilder = crunchifyDocBuilderFactory . newDocumentBuilder ( ) ; // The Document interface represents the entire HTML or XML document. Document crunchifyDoc = crunchifyDocBuilder . newDocument ( ) ; // The Element interface represents an element in an HTML or XML document. Element mainRootElement = crunchifyDoc . createElementNS ( "https://crunchify.com/CrunchifyCreateXMLDOM" , "Companies" ) ; // Adds the node newChild to the end of the list of children of this node. // If the newChild is already in the tree, it is first removed. crunchifyDoc . appendChild ( mainRootElement ) ; // append child elements to root element mainRootElement . appendChild ( getCompany ( crunchifyDoc , "1" , "Paypal" , "Payment" , "1000" ) ) ; mainRootElement . appendChild ( getCompany ( crunchifyDoc , "2" , "Amazon" , "Shopping" , "2000" ) ) ; mainRootElement . appendChild ( getCompany ( crunchifyDoc , "3" , "Google" , "Search" , "3000" ) ) ; mainRootElement . appendChild ( getCompany ( crunchifyDoc , "4" , "Crunchify" , "Java Tutorials" , "10" ) ) ; // output DOM XML to console // An instance of this abstract class can transform a source tree into a result tree. Transformer crunchifyTransformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; crunchifyTransformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; // Acts as a holder for a transformation Source tree in the form of a Document Object Model (DOM) tree. DOMSource source = new DOMSource ( crunchifyDoc ) ; // Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup. StreamResult console = new StreamResult ( System . out ) ; crunchifyTransformer . transform ( source , console ) ; System . out . println ( "\nTutorial by Crunchify. XML DOM Created Successfully.." ) ; } catch ( TransformerException | ParserConfigurationException e ) { e . printStackTrace ( ) ; } } // The Node interface is the primary datatype for the entire Document Object Model. // It represents a single node in the document tree. private static Node getCompany ( Document doc , String id , String name , String age , String role ) { Element crunchifyCompany = doc . createElement ( "Company" ) ; crunchifyCompany . setAttribute ( "id" , id ) ; crunchifyCompany . appendChild ( getCrunchifyCompanyElements ( doc , crunchifyCompany , "Name" , name ) ) ; crunchifyCompany . appendChild ( getCrunchifyCompanyElements ( doc , crunchifyCompany , "Type" , age ) ) ; crunchifyCompany . appendChild ( getCrunchifyCompanyElements ( doc , crunchifyCompany , "Employees" , role ) ) ; return crunchifyCompany ; } // Utility method to create text node private static Node getCrunchifyCompanyElements ( Document doc , Element element , String name , String value ) { Element node = doc . createElement ( name ) ; node . appendChild ( doc . createTextNode ( value ) ) ; return node ; } } |
문서 빌더팩토리:
응용 프로그램이 XML 문서에서 DOM 개체 트리를 생성하는 파서를 얻을 수 있도록 하는 팩토리 API를 정의합니다.

문서 작성기:
XML 문서에서 DOM 문서 인스턴스를 가져오는 API를 정의합니다.
추가자식():
이 노드의 자식 목록 끝에 newChild 노드를 추가합니다. newChild가 이미 트리에 있으면 먼저 제거됩니다.
변신 로봇:
이 추상 클래스의 인스턴스는 소스 트리를 결과 트리로 변환할 수 있습니다.
DOM 소스:
DOM(문서 개체 모델) 트리 형식의 변환 소스 트리에 대한 홀더 역할을 합니다.
스트림 결과:
XML, 일반 텍스트, HTML 또는 기타 마크업 형식이 될 수 있는 변환 결과에 대한 홀더 역할을 합니다.
-
The Node
인터페이스는 전체 문서 개체 모델에 대한 기본 데이터 유형입니다. 문서 트리의 단일 노드를 나타냅니다. -
The Document
인터페이스는 전체 HTML 또는 XML 문서를 나타냅니다. -
The Element
Java 인터페이스는 HTML 또는 XML 문서의 요소를 나타냅니다.
Eclipse 콘솔 출력:
위의 프로그램을 Java Application으로 실행하면 아래와 같은 결과를 얻을 수 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<? xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> < Companies xmlns = "https://crunchify.com/CrunchifyCreateXMLDOM" > < Company id = "1" > < Name > Paypal < / Name > < Type > Payment < / Type > < Employees > 1000 < / Employees > < / Company > < Company id = "2" > < Name > Amazon < / Name > < Type > Shopping < / Type > < Employees > 2000 < / Employees > < / Company > < Company id = "3" > < Name > Google < / Name > < Type > Search < / Type > < Employees > 3000 < / Employees > < / Company > < Company id = "4" > < Name > Crunchify < / Name > < Type > Java Tutorials < / Type > < Employees > 10 < / Employees > < / Company > < / Companies > Tutorial by Crunchify . XML DOM Created Successfully . . Process finished with exit code 0 |