Sharecs.net
  • Trang chủ
  • Thủ Thuật
    • Thủ thuật máy tính
      • Windows
      • MacOS
      • Linux
    • Thủ thuật internet
    • Thủ thuật phần mềm
  • 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
No Result
View All Result
  • Trang chủ
  • Thủ Thuật
    • Thủ thuật máy tính
      • Windows
      • MacOS
      • Linux
    • Thủ thuật internet
    • Thủ thuật phần mềm
  • 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
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

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

Nguyễn Tuấn by Nguyễn Tuấn
01/03/2022
1
0
SHARES
109
VIEWS

Mình sử dụng SAX Parser để phân tích XML và ghi lại được thông báo lỗi sau:

org.xml.sax.SAXParseException; systemId: ../src/main/resources/staff.xml;

  lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

Khi văn bản không hợp lệ hoặc BOM trước khai báo XML hoặc mã hóa khác sẽ gây ra SAX Error – Content is not allowed in prolog.

Mục Lục

  • 1 Văn bản không hợp lệ trước khai báo XML.
  • 2 BOM ở đầu tệp XML gây SAX Error
    • 2.1 Xóa BOM trong code
    • 2.2 Trong notepad ++, chọn Mã hóa UTF-8 without BOM.
    • 2.3 Trong Intellij IDE, ngay trên tệp, chọnRemove BOM.
  • 3 Định dạng mã hóa khác nhau

Văn bản không hợp lệ trước khai báo XML.

Invalid text before the XML declaration hay là văn bản không hợp lệ trước khai báo XML. Khi chúng ta khai báo XML, bất kỳ văn bản nào cũng sẽ gây ra Content is not allowed in prolog lỗi.

Ví dụ: File XML bên dưới chứa thêm một dấu chấm nhỏ ” . ” trước phần khai báo XML.

.<?xml version="1.0" encoding="utf-8"?>
<company>
    <staff>
        <firstname>yong</firstname>
        <lastname>mook kim</lastname>
        <nickname>sharecs</nickname>
        <salary>100000</salary>
    </staff>
</company>

Để sửa nó: Xóa bất kỳ văn bản nào trước khai báo XML.

BOM ở đầu tệp XML gây SAX Error

Nhiều trình soạn thảo văn bản tự động thêm BOM vào tệp UTF-8.

Lưu ý: Các bạn nên đọc qua các bài viết sau Wikipedia – Dấu thứ tự Byte (BOM)

Được thử nghiệm với Java 11 và Java 8, SAX Parser tích hợp có thể phân tích cú pháp tệp BOM UTF-8 một cách chính xác; tuy nhiên, một số nhà phát triển cho rằng BOM đã gây ra lỗi khi phân tích cú pháp XML.

Để khắc phục , hãy xóa BOM khỏi tệp UTF-8.

Xóa BOM trong code

Ví dụ dưới đây ByteBuffer để xóa BOM khỏi tệp UTF-8.

P/S: Một số trình phân tích cú pháp XML, JSON, CSV có thể không phân tích cú pháp hoặc xử lý file nếu nó chứa BOM trong tệp UTF-8; thông thường phải xóa hoặc bỏ qua BOM trước khi phân tích cú pháp tệp.

package com.sharecs.io.howto;

import org.apache.commons.codec.binary.Hex;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class RemoveBomFromUtf8File {

  public static void main(String[] args) throws IOException {

      Path path = Paths.get("/home/sharecs/file.txt");
      writeBomFile(path, "sharecs");
      removeBom(path);

  }

  private static void writeBomFile(Path path, String content) {
      // Java 8 default UTF-8
      try (BufferedWriter bw = Files.newBufferedWriter(path)) {
          bw.write("\ufeff");
          bw.write(content);
          bw.newLine();
          bw.write(content);
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

  private static boolean isContainBOM(Path path) throws IOException {

      if (Files.notExists(path)) {
          throw new IllegalArgumentException("Path: " + path + " does not exists!");
      }

      boolean result = false;

      byte[] bom = new byte[3];
      try (InputStream is = new FileInputStream(path.toFile())) {

          // read 3 bytes of a file.
          is.read(bom);

          // BOM encoded as ef bb bf
          String content = new String(Hex.encodeHex(bom));
          if ("efbbbf".equalsIgnoreCase(content)) {
              result = true;
          }

      }

      return result;
  }

  private static void removeBom(Path path) throws IOException {

      if (isContainBOM(path)) {

          byte[] bytes = Files.readAllBytes(path);

          ByteBuffer bb = ByteBuffer.wrap(bytes);

          System.out.println("Found BOM!");

          byte[] bom = new byte[3];
          // get the first 3 bytes
          bb.get(bom, 0, bom.length);

          // remaining
          byte[] contentAfterFirst3Bytes = new byte[bytes.length - 3];
          bb.get(contentAfterFirst3Bytes, 0, contentAfterFirst3Bytes.length);

          System.out.println("Remove the first 3 bytes, and overwrite the file!");

          // override the same path
          Files.write(path, contentAfterFirst3Bytes);

      } else {
          System.out.println("This file doesn't contains UTF-8 BOM!");
      }

  }

}

Kết quả

Found BOM!
Remove the first 3 bytes, and overwrite the file!
Trong notepad ++, chọn Mã hóa UTF-8 without BOM.
Trong Intellij IDE, ngay trên tệp, chọnRemove BOM.

Định dạng mã hóa khác nhau

Cách mã hóa khác cũng khiến XML phổ biến Content is not allowed in prolog.

Ví dụ: file XML UTF-8.

<?xml version="1.0" encoding="utf-8"?>
<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="EUR">8000</salary>
        <bio><![CDATA[a & b]]></bio>
    </staff>
</Company>

Và chúng ta sử dụng mã hóa UTF-16 để phân tích cú pháp tệp XML mã hóa UTF-8 ở trên.


  SAXParserFactory factory = SAXParserFactory.newInstance();

  try (InputStream is = getXMLFileAsStream()) {

      SAXParser saxParser = factory.newSAXParser();

      // parse XML and map to object, it works, but not recommend, try JAXB
      MapStaffObjectHandlerSax handler = new MapStaffObjectHandlerSax();

      // more options for configuration
      XMLReader xmlReader = saxParser.getXMLReader();
      xmlReader.setContentHandler(handler);

      InputSource source = new InputSource(is);

      // UTF-16 to parse an UTF-8 XML file
      source.setEncoding(StandardCharsets.UTF_16.toString());
      xmlReader.parse(source);

      // print all
      List<Staff> result = handler.getResult();
      result.forEach(System.out::println);

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

Kết quả

[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1243)
at java.xml/com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:635)
at com.sharecs.xml.sax.ReadXmlSaxParser2.main(ReadXmlSaxParser2.java:45)

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

5/5 - (1 bình chọn)
Tags: javajava xmlread xmlsax errorsax parserxml
ShareSendTweetShare

Cùng chuyên mục

Annotations @Controller and @RestController Trong Spring

Annotations @Controller and @RestController Trong Spring

05/02/2023
8
How to Convert String to XML in Java ?

How to Convert String to XML in Java ?

19/01/2023
6
Đồ Án Tốt Nghiệp Quản Lý Trang Thiết Bị && Full Báo Cáo

Đồ Án Tốt Nghiệp Quản Lý Trang Thiết Bị && Full Báo Cáo

11/12/2022
25
How To Import Excel Spring Boot – Trả Lỗi Trong File

How To Import Excel Spring Boot – Trả Lỗi Trong File

30/11/2022
39
Subscribe
Notify of
guest

guest

1 Comment
Newest
Oldest Most Voted
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
  • Hatsune Miku Anime Wallpaper Video 4k

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

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

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

    45 shares
    Share 0 Tweet 0
  • Trending
  • Comments
  • Latest
Hatsune Miku Anime Wallpaper Video 4k

Hatsune Miku Anime Wallpaper Video 4k

30/01/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
Download Video Wallpaper Agatsuma Zenitsu – Anime Kimetsu No Yaiba

Download Video Wallpaper Agatsuma Zenitsu – Anime Kimetsu No Yaiba

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

Thư viện đồ họa trong Python – Vẽ doraemon

09/12/2020
Cách Kích Hoạt Key Win 11 Bản Quyền –Active Win 11 – Win 10 Free

Cách Kích Hoạt Key Win 11 Bản Quyền –Active Win 11 – Win 10 Free

1
Annotations @Controller and @RestController Trong Spring

Annotations @Controller and @RestController Trong Spring

05/02/2023
Sự Cố Năm 2038 – Lỗi Đồng Hồ Trên Máy Tính

Sự Cố Năm 2038 – Lỗi Đồng Hồ Trên Máy Tính

05/02/2023
5 cách mà máy ảnh sẽ phát triển vào năm 2023 – Tốt và Xấu

5 cách mà máy ảnh sẽ phát triển vào năm 2023 – Tốt và Xấu

22/01/2023
Tòa án Ấn Độ bác bỏ yêu cầu của Google để chặn phán quyết chống độc quyền Android

Tòa án Ấn Độ bác bỏ yêu cầu của Google để chặn phán quyết chống độc quyền Android

21/01/2023

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

  • Crom trong Cách Kích Hoạt Key Win 11 Bản Quyền –Active Win 11 – Win 10 Free
  • ngu trong Anime Wallpaper Video 4k – Anime Kanao Tsuyuri Kimetsu no Yaiba
  • thiem trong Share Phôi Chứng Minh Nhân Dân PSD
  • Nguyễn Tuấn trong Ứng Dụng Thuật Toán Hồi Quy Tuyến Tính Để Chẩn Đoán Xơ Vữa Động Mạch 2021

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ủ
  • Thủ Thuật
    • Thủ thuật máy tính
      • Windows
      • MacOS
      • Linux
    • Thủ thuật internet
    • Thủ thuật phần mềm
  • 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

CopyRight By Sharecs.net DMCA.com Protection Status