Sharecs.net
  • Trang chủ
  • Kho Tài Liệu – Báo Cáo
  • Thủ Thuật
    • Thủ thuật máy tính
      • Windows
      • MacOS
      • Linux
    • Thủ thuật internet
    • Thủ thuật phần mềm
  • Lỗi máy tính
    • Lỗi internet
    • Lỗi windows
    • Lỗi phần mềm
  • Lập Trình
    • Lập Trình Java
    • Lập trình Python
    • Lập Trình React Native
    • Code Hay
  • Linh Tinh
    • PhotoShop
    • Tải Video Wallpaper
    • Kho Tools
      • Cân Bằng Phương Trình Hóa Học
      • Custom Css Scrollbar – Render Code
      • Tạo Kí Tự Đặc Biệt Online
      • Tạo Deep Link
    • Tài Liệu – Luận Văn – Báo Cáo
    • Kho Theme Website WordPress
    • Phần Mềm
No Result
View All Result
  • Trang chủ
  • Kho Tài Liệu – Báo Cáo
  • Thủ Thuật
    • Thủ thuật máy tính
      • Windows
      • MacOS
      • Linux
    • Thủ thuật internet
    • Thủ thuật phần mềm
  • Lỗi máy tính
    • Lỗi internet
    • Lỗi windows
    • Lỗi phần mềm
  • Lập Trình
    • Lập Trình Java
    • Lập trình Python
    • Lập Trình React Native
    • Code Hay
  • Linh Tinh
    • PhotoShop
    • Tải Video Wallpaper
    • Kho Tools
      • Cân Bằng Phương Trình Hóa Học
      • Custom Css Scrollbar – Render Code
      • Tạo Kí Tự Đặc Biệt Online
      • Tạo Deep Link
    • Tài Liệu – Luận Văn – Báo Cáo
    • Kho Theme Website WordPress
    • Phần Mềm
No Result
View All Result
Sharecs.net
No Result
View All Result
Home Lập Trình Lập Trình Java Java XML Tutorial

Cách Viết File XML Trong Java – (DOM Parser)

by Nguyễn Tuấn
08/02/2022

Trong bài viết này mình sẽ hướng dẫn các bạn sử dụng API DOM tích hợp sẵn của Java để ghi dữ liệu vào tệp XML.

Mục Lục

  • Ghi XML vào một file
  • Pretty Print XML ( Hiển thị XML đẹp )
  • Viết các phần tử XML, thuộc tính, nhận xét CDATA, v.v.
  • Câu hỏi thường gặp về DOM
    • Làm cách nào để tắt khai báo XML?
    • Làm cách nào để thay đổi mã hóa XML?
    • Làm cách nào để hiển thị XML đẹp?
    • Làm cách nào để ẩn khai báo XML ‘standalone =” no ” ‘?
    • Làm cách nào để thay đổi phiên bản khai báo XML?

Ghi XML vào một file

Các bước tạo và ghi XML vào file.

  1. Tạo một Document doc.
  2. Tạo các phần tử XML, thuộc tính, v.v. và nối vào Document doc.
  3. Tạo một Transformer để ghi Document doc vào một OutputStream.
package com.sharecs.xml.dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.OutputStream;

public class WriteXmlDom1 {

    public static void main(String[] args)
            throws ParserConfigurationException, TransformerException {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("company");
        doc.appendChild(rootElement);

        doc.createElement("staff");
        rootElement.appendChild(doc.createElement("staff"));

        //...create XML elements, and others...

        // write dom document to a file
        try (FileOutputStream output =
                     new FileOutputStream("c:\\test\\staff-dom.xml")) {
            writeXml(doc, output);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // write doc to output stream
    private static void writeXml(Document doc,
                                 OutputStream output)
            throws TransformerException {

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(output);

        transformer.transform(source, result);

    }
}

Output

<?xml version="1.0" encoding="UTF-8" standalone="no"?><company><staff>sharecs</staff></company>

Pretty Print XML ( Hiển thị XML đẹp )

Theo mặc định, Transformer đầu ra XML ở định dạng nhỏ gọn.

<?xml version="1.0" encoding="UTF-8" standalone="no"?><company><staff>sharecs</staff></company>

Chúng ta có thể cài đặt OutputKeys.INDENT để Transformer kích hoạt định dạng hiển thị XML đẹp hơn.

  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();

  // pretty print XML
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

  DOMSource source = new DOMSource(doc);
  StreamResult result = new StreamResult(output);

  transformer.transform(source, result);

Kết quả:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
  <staff>sharecs</staff>
</company>

Viết các phần tử XML, thuộc tính, nhận xét CDATA, v.v.

Ví dụ dưới đây sử dụng DOM Parser để tạo và ghi XML vào một OutputStream.

package com.sharecs.xml.dom;

import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class WriteXmlDom3 {

  public static void main(String[] args)
          throws ParserConfigurationException, TransformerException {

      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

      // root elements
      Document doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("company");
      doc.appendChild(rootElement);

      // staff 1001

      // add xml elements
      Element staff = doc.createElement("staff");
      // add staff to root
      rootElement.appendChild(staff);
      // add xml attribute
      staff.setAttribute("id", "1001");

      // alternative
      // Attr attr = doc.createAttribute("id");
      // attr.setValue("1001");
      // staff.setAttributeNode(attr);

      Element name = doc.createElement("name");
      // JDK 1.4
      //name.appendChild(doc.createTextNode("sharecs"));
      // JDK 1.5
      name.setTextContent("sharecs");
      staff.appendChild(name);

      Element role = doc.createElement("role");
      role.setTextContent("support");
      staff.appendChild(role);

      Element salary = doc.createElement("salary");
      salary.setAttribute("currency", "USD");
      salary.setTextContent("5000");
      staff.appendChild(salary);

      // add xml comment
      Comment comment = doc.createComment(
              "for special characters like < &, need CDATA");
      staff.appendChild(comment);

      Element bio = doc.createElement("bio");
      // add xml CDATA
      CDATASection cdataSection =
              doc.createCDATASection("HTML tag <code>testing</code>");
      bio.appendChild(cdataSection);
      staff.appendChild(bio);

      // staff 1002
      Element staff2 = doc.createElement("staff");
      // add staff to root
      rootElement.appendChild(staff2);
      staff2.setAttribute("id", "1002");

      Element name2 = doc.createElement("name");
      name2.setTextContent("yflow");
      staff2.appendChild(name2);

      Element role2 = doc.createElement("role");
      role2.setTextContent("admin");
      staff2.appendChild(role2);

      Element salary2 = doc.createElement("salary");
      salary2.setAttribute("currency", "EUD");
      salary2.setTextContent("8000");
      staff2.appendChild(salary2);

      Element bio2 = doc.createElement("bio");
      // add xml CDATA
      bio2.appendChild(doc.createCDATASection("a & b"));
      staff2.appendChild(bio2);

      // print XML to system console
      writeXml(doc, System.out);

  }

  // write doc to output stream
  private static void writeXml(Document doc,
                               OutputStream output)
          throws TransformerException {

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();

      // pretty print
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");

      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(output);

      transformer.transform(source, result);

  }
}

Kết quả:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
  <staff id="1001">
      <name>sharecs</name>
      <role>support</role>
      <salary currency="USD">5000</salary>
      <!--for special characters like < &, need CDATA-->
      <bio>
          <![CDATA[HTML tag <code>testing</code>]]>
      </bio>
  </staff>
  <staff id="1002">
      <name>yflow</name>
      <role>admin</role>
      <salary currency="EUD">8000</salary>
      <bio>
          <![CDATA[a & b]]>
      </bio>
  </staff>
</company>

Câu hỏi thường gặp về DOM

Làm cách nào để tắt khai báo XML?

Chúng ta có thể cấu hình OutputKeys.OMIT_XML_DECLARATION để loại bỏ khai báo XML.

 // hide the xml declaration
  // hide <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
Làm cách nào để thay đổi mã hóa XML?

Chúng ta có thể định cấu hình OutputKeys.ENCODING để thay đổi mã hóa XML.

  // set xml encoding
  // <?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
  transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
Làm cách nào để hiển thị XML đẹp?

Chúng ta có thể định cấu hình OutputKeys.INDENT để kích hoạt XML bản hiển thị đẹp.

  // pretty print
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
Làm cách nào để ẩn khai báo XML ‘standalone =” no ” ‘?

Chúng ta có thể cấu hình document.setXmlStandalone(true) để ẩn khai báo XML standalone=”no”.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();

  // pretty print
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

  // hide the standalone="no"
  doc.setXmlStandalone(true);

  DOMSource source = new DOMSource(doc);
  StreamResult result = new StreamResult(output);

  transformer.transform(source, result);
Làm cách nào để thay đổi phiên bản khai báo XML?

Chúng ta có thể cấu hình document.setXmlVersion(“version”) để thay đổi phiên bản khai báo XML.

 // set xml version
  // <?xml version="1.1" encoding="ISO-8859-1" standalone="no"?>
  doc.setXmlVersion("1.1");

Cảm ơn các bạn đã ghé thăm. Chúc các bạn thành công!

Đánh giá bài viết giúp mình nhé!
Tags: domjava xmlwrite xmlxml
ShareSendTweetShare

Cùng chuyên mục

How to Convert String to XML in Java ?

How to Convert String to XML in Java ?

19/01/2023
8
Cách Đọc File XML Java ( DOM Parser )

SAX Error – Nội dung không được phép trong phần mở đầu

01/03/2022
113
Cách đọc file XML UTF-8 trong Java – (SAX Parser)

Cách đọc file XML UTF-8 trong Java – (SAX Parser)

01/03/2022
86
Cách đọc file XML trong Java (SAX Parser)

Cách đọc file XML trong Java (SAX Parser)

13/02/2022
165
Cách Đọc File XML Java ( DOM Parser )

Các Ví Dụ Về XML Và XSLT Của Java DOM Parser

09/02/2022
21
Cách Đọc File XML Java ( DOM Parser )

Hiển Thị File XML Đẹp Với Java Dom và XSLT

09/02/2022
32
Load More
Subscribe
Notify of
guest

guest

0 Comments
Inline Feedbacks
View all comments

Tài nguyên

Cân bằng phương trình phản ứng hóa

Tạo deep link

Custom Css Scrollbar – Render Code

Bài Viết Nổi Bật

  • Bài Tập Code Python Đơn Giản Có Lời Giải – Phần 1

    Bài Tập Code Python Đơn Giản Có Lời Giải – Phần 1

    1 shares
    Share 0 Tweet 0
  • Download Video Wallpaper Agatsuma Zenitsu – Anime Kimetsu No Yaiba

    45 shares
    Share 0 Tweet 0
  • Trắc Nghiệm Mạng Máy Tính Phần 3 Có Đáp Án

    0 shares
    Share 0 Tweet 0
  • 500 Câu Trắc Nghiệm Mạng Máy Tính Phần 1 Có Đáp Án

    0 shares
    Share 0 Tweet 0
  • Hướng Dẫn React Native Build apk File

    0 shares
    Share 0 Tweet 0
  • Trending
  • Comments
  • Latest
Download Video Wallpaper Agatsuma Zenitsu – Anime Kimetsu No Yaiba

Download Video Wallpaper Agatsuma Zenitsu – Anime Kimetsu No Yaiba

19/02/2023
Bài Tập Code Python Đơn Giản Có Lời Giải – Phần 1

Bài Tập Code Python Đơn Giản Có Lời Giải – Phần 1

31/08/2020
500 Câu Trắc Nghiệm Mạng Máy Tính Phần 1 Có Đáp Án

500 Câu Trắc Nghiệm Mạng Máy Tính Phần 1 Có Đáp Án

23/08/2021
Hướng dẫn cài đặt React Native trên Windows – Phần 1

Hướng Dẫn React Native Build apk File

14/11/2020
Thư viện đồ họa trong Python – Source Code Bắn Pháo Hoa

Thư viện đồ họa trong Python – Source Code Bắn Pháo Hoa

18/03/2023
Chia sẻ quá trình để xây dựng 1 group Facebook cho newbie

Chia sẻ quá trình để xây dựng 1 group Facebook cho newbie

18/03/2023
Tính tổng – Two Sum Leetcode

Tính tổng – Two Sum Leetcode

14/03/2023
So sánh If Else và Switch Case

So sánh If Else và Switch Case

21/02/2023

Phản hồi gần đây

  • luan trong Thư viện đồ họa trong Python – Vẽ doraemon
  • tuan trong Nhận Diện Chó Mèo Python – Tensorflow – Neural Network – Deep Learning
  • Lê Thị Vân trong Fake Giấy Tờ Xác Minh Doanh Nghiệp Trên Facebook
  • Crom trong Cách Kích Hoạt Key Win 11 Bản Quyền –Active Win 11 – Win 10 Free

Donate

Mời Share’cs ly Cafe 

Liên hệ quảng cáo

Email: Sharecs.net@gmail.com

Hợp tác nội dung: Sharecs rất vinh dự được mời các bạn đóng góp những sản phẩm thiết kế, thủ thuật hay những chia sẻ hữu ích… để cùng chia sẻ rộng rãi tới mọi người!

Giới Thiệu

Sharecs.net là một website/blog cá nhân, chuyên chia sẻ những kiến thức xoay quanh công nghệ như máy tính, internet, phần mềm, lập trình,... Mình hi vọng, Sharecs sẽ mang lại những kiến thức mà bạn chưa từng được học trên ghế nhà trường!

  • Giới Thiệu & Liên Hệ
  • Chính Sách Bảo Mật

CopyRight By Sharecs.net DMCA.com Protection Status

No Result
View All Result
  • Trang chủ
  • Kho Tài Liệu – Báo Cáo
  • Thủ Thuật
    • Thủ thuật máy tính
      • Windows
      • MacOS
      • Linux
    • Thủ thuật internet
    • Thủ thuật phần mềm
  • Lỗi máy tính
    • Lỗi internet
    • Lỗi windows
    • Lỗi phần mềm
  • Lập Trình
    • Lập Trình Java
    • Lập trình Python
    • Lập Trình React Native
    • Code Hay
  • Linh Tinh
    • PhotoShop
    • Tải Video Wallpaper
    • Kho Tools
      • Cân Bằng Phương Trình Hóa Học
      • Custom Css Scrollbar – Render Code
      • Tạo Kí Tự Đặc Biệt Online
      • Tạo Deep Link
    • Tài Liệu – Luận Văn – Báo Cáo
    • Kho Theme Website WordPress
    • Phần Mềm

CopyRight By Sharecs.net DMCA.com Protection Status