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

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

by Nguyễn Tuấn
22/04/2023

Bài viết này hướng dẫn cách sử dụng Java DOM Parser + XSLT để định dạng hoặc in ấn một tài liệu XML.

Mục Lục

  • Một File XML
  • Hiển Thị File XML Thông Qua Transformer
  • Hiển Thị File XML khá đẹp qua XSLT

Một File XML

<?xml version="1.0" encoding="utf-8"?>
<company>
    <staff id="1001">
        <name>sharecs</name>
        <role>support</role>
    </staff>
    <staff id="1002">
        <name>yflow</name>
        <role>admin</role>
    </staff>
</company>

Hiển Thị File XML Thông Qua Transformer

Trong javax.xml.transform.Transformer, chúng ta có thể cấu hình thuộc tính OutputKeys.INDENT để in các tài liệu XML.

  private static void transform(Document doc, OutputStream output)
          throws TransformerException {

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

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

      transformer.transform(new DOMSource(doc), new StreamResult(output));

  }

Kết quả:


<?xml version="1.0" encoding="utf-8" standalone="no"?>
<company>

  <staff id="1001">

      <name>sharecs</name>

      <role>support</role>

  </staff>

  <staff id="1002">

      <name>yflow</name>

      <role>admin</role>

  </staff>

</company>

Tuy nhiên, Transformer sẽ thêm nhiều dòng mới trống (được thử nghiệm trong Java 11) trong đầu ra, mình không chắc chắn tại sao?

Hiển Thị File XML khá đẹp qua XSLT

Để giải quyết vấn đề dòng mới trống thừa ở trên, chúng ta có thể thêm một xslt tệp để chuyển đổi bản hiển thị đẹp.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" cdata-section-elements="cdata-other-elements"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Ví dụ về trình phân tích cú pháp DOM cho phép chuyển đổi XSLT.

package com.sharecs.xml.dom.xslt;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

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 javax.xml.transform.stream.StreamSource;
import java.io.*;

public class XsltPrettyPrintDomParser {

  private static final String XML_FILENAME
                          = "src/main/resources/staff-simple.xml";
  private static final String XSLT_FILENAME
                          = "src/main/resources/xslt/staff-format.xslt";

  public static void main(String[] args) {

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      try (InputStream is = new FileInputStream(XML_FILENAME)) {

          DocumentBuilder db = dbf.newDocumentBuilder();

          Document doc = db.parse(is);

          transform(doc, System.out);


      } catch (IOException | ParserConfigurationException |
              SAXException | TransformerException e) {
          e.printStackTrace();
      }

  }

  private static void transform(Document doc, OutputStream output)
          throws TransformerException {

      TransformerFactory transformerFactory = TransformerFactory.newInstance();

      //Transformer transformer = transformerFactory.newTransformer();

      // add XSLT for pretty print
      Transformer transformer = transformerFactory.newTransformer(
              new StreamSource(new File(XSLT_FILENAME)));

      // pretty print, this will add extra new lines
      // transformer.setOutputProperty(OutputKeys.INDENT, "yes");

      // add extra standalone to break the root node to a new line
      transformer.setOutputProperty(OutputKeys.STANDALONE, "no");

      transformer.transform(new DOMSource(doc), new StreamResult(output));

  }

}

Kết quả:


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
  <staff id="1001">
      <name>sharecs</name>
      <role>support</role>
  </staff>
  <staff id="1002">
      <name>yflow</name>
      <role>admin</role>
  </staff>
</company>

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 xmlread xmltransform xmlxmlxslt
ShareSendTweetShare

Cùng chuyên mục

How to Convert String to XML in Java ?

How to Convert String to XML in Java ?

22/04/2023
10
Cách Đọc File XML Java ( DOM Parser )

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

22/04/2023
119
Cách đọc file XML UTF-8 trong Java – (SAX Parser)

Parser SAX – Invalid Byte 1 of 1-Byte UTF-8 Sequence

22/04/2023
46
Cách đọc file XML UTF-8 trong Java – (SAX Parser)

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

22/04/2023
98
Cách đọc file XML trong Java (SAX Parser)

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

22/04/2023
193
Cách Đọc File XML Java ( DOM Parser )

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

22/04/2023
25
Load More

Tài nguyên

Luận văn báo cáo giá rẻ

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

  • Download Video Wallpaper Agatsuma Zenitsu – Anime Kimetsu No Yaiba

    Download Video Wallpaper Agatsuma Zenitsu – Anime Kimetsu No Yaiba

    45 shares
    Share 0 Tweet 0
  • Nhận Diện Chó Mèo Python – Tensorflow – Neural Network – Deep Learning

    0 shares
    Share 0 Tweet 0
  • Thư viện đồ họa trong Python – Vẽ doraemon

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

    1 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

7 Cấu Trúc Dữ Liệu Quan Trọng Mà Lập Trình Viên Không Thể Bỏ Qua

Tính tổng – Two Sum Leetcode

Kinh Nghiệm Và Câu Hỏi Phỏng Vấn SEO

Cách Đăng Ký Telegram Premium Giá Rẻ Chỉ 17k

Convert Long To BigDecimal In Java

Tool Active Win 10 Pro Và Active Office

  • 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

This website uses cookies. By continuing to use this website you are giving consent to cookies being used. Visit our Privacy and Cookie Policy.