如何使用 Java SAX 读取 XML 声明

How to read XML declaration with Java SAX

我想使用 Java SAX 从 XML 文件中读取 XML 声明。例如

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

我尝试使用 DefaultHandler,但没有为 XML 声明调用字符和 startElement。这是我的代码:

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXStuff {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
        sp.parse("test.xml", new DefaultHandler() {
            public void characters(char[] ch, int start, int length) throws SAXException {
                for(int i = start; i < start + length; i++) {
                    System.out.print(ch[i]);
                }
            }
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                System.out.println(qName);
            }
        });
    }
}

如何在 Java 中使用 SAX 获取 XML 声明?

由于 Java 14,org.xml.sax.ContentHandler has a declaration method for this purpose. DefaultHandler 实现了 ContentHandler,因此可以覆盖此方法以提供自定义操作。

这是方法签名:

void declaration​(String version, String encoding, String standalone) throws SAXException

version - the version string as in the input document, null if not specified
encoding - the encoding string as in the input document, null if not specified
standalone - the standalone string as in the input document, null if not specified

示例:

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler(){
    @Override
    public void declaration(String version, String encoding, String standalone) {
        String declaration = "<?xml "
                + (version != null ? "version=\"" + version + "\"": "")
                + (encoding != null ? " encoding=\"" + encoding + "\"": "")
                + (standalone != null ? " standalone=\"" + standalone + "\"": "")
                + "?>";
        System.out.println(declaration);
    }
};
parser.parse(new File("file.xml"), handler);