Java : LSSerializer (XML) 示例

LSSerializer (Java SE 22 & JDK 22) 示例。
您将在大多数 LSSerializer 方法中找到代码示例。

注解 :

  • 本文可能使用了翻译软件以方便阅读。 另请查看英文原文

简介

LSSerializer 提供用于将 DOM 文档序列化(写入)为 XML 的 API。XML 数据将写入字符串或输出流。序列化过程中所做的任何更改或修正都只会影响序列化的数据。序列化操作永远不会改变 Document 对象及其子对象。 (机器翻译)

Class diagram

final var xml = """
        <!DOCTYPE root [
            <!ENTITY aaa "bbb">
        ]>
        <root>&aaa;</root>
        """;

final var factory = DocumentBuilderFactory.newInstance();
factory.setExpandEntityReferences(false);

final var builder = factory.newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var domImpl = builder.getDOMImplementation();

final var feature = domImpl.getFeature("LS", "3.0");
if (feature instanceof DOMImplementationLS ls) {
    final var serializer = ls.createLSSerializer();
    final var str = serializer.writeToString(document);
    System.out.println(str);

    // Result
    // ↓
    //<?xml version="1.0" encoding="UTF-16"?><!DOCTYPE root [
    //<!ENTITY aaa 'bbb'>
    //]>
    //<root>&aaa;</root>
}

Methods

DOMConfiguration getDomConfig ()

LSSerializer 在序列化 DOM 节点时使用的 DOMConfiguration 对象。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var domImpl = builder.getDOMImplementation();

final var feature = domImpl.getFeature("LS", "3.0");
if (feature instanceof DOMImplementationLS ls) {
    final var serializer = ls.createLSSerializer();
    final var domConfig = serializer.getDomConfig();

    final var names = domConfig.getParameterNames();
    for (int i = 0; i < names.getLength(); i++) {
        final var name = names.item(i);
        final var param = domConfig.getParameter(name);
        System.out.println(name + " : " + param);
    }

    // Result
    // ↓
    //canonical-form : false
    //cdata-sections : true
    //check-character-normalization : false
    //comments : true
    //datatype-normalization : false
    //element-content-whitespace : true
    //entities : true
    //infoset : false
    //namespaces : true
    //namespace-declarations : true
    //split-cdata-sections : true
    //validate : false
    //validate-if-schema : false
    //well-formed : true
    //discard-default-content : true
    //format-pretty-print : false
    //ignore-unknown-character-denormalizations : true
    //xml-declaration : true
    //http://www.oracle.com/xml/jaxp/properties/isStandalone : false
    //jdk.xml.isStandalone : false
    //error-handler : null
}

LSSerializerFilter getFilter ()

当应用程序提供过滤器时,序列化器将在序列化每个节点之前调用该过滤器。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var domImpl = builder.getDOMImplementation();

final var feature = domImpl.getFeature("LS", "3.0");
if (feature instanceof DOMImplementationLS ls) {

    final var xml = """
            <root>
              <child><aaa/><bbb/><ccc/></child>
            </root>
            """;

    final var input = ls.createLSInput();
    input.setStringData(xml);

    final var parser = ls.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
    final var document = parser.parse(input);

    final var serializer = ls.createLSSerializer();
    System.out.println(serializer.getFilter()); // null

    //<?xml version="1.0" encoding="UTF-16"?><root>
    //  <child><aaa/><bbb/><ccc/></child>
    //</root>
    System.out.println(serializer.writeToString(document));

    final var filter = new LSSerializerFilter() {
        @Override
        public short acceptNode(Node n) {
            System.out.println("acceptNode : " + n);

            if (n.getNodeName().equals("bbb")) {
                return NodeFilter.FILTER_REJECT;
            } else {
                return NodeFilter.FILTER_ACCEPT;
            }
        }

        @Override
        public int getWhatToShow() {
            return NodeFilter.SHOW_ELEMENT;
        }
    };

    serializer.setFilter(filter);
    System.out.println(filter == serializer.getFilter()); // true

    System.out.println("-- write start --");

    final var ret = serializer.writeToString(document);

    System.out.println("-- write end --");
    System.out.println(ret);

    // Result
    // ↓
    //-- write start --
    //acceptNode : [root: null]
    //acceptNode : [child: null]
    //acceptNode : [aaa: null]
    //acceptNode : [aaa: null]
    //acceptNode : [bbb: null]
    //acceptNode : [bbb: null]
    //acceptNode : [ccc: null]
    //acceptNode : [ccc: null]
    //acceptNode : [child: null]
    //acceptNode : [root: null]
    //-- write end --
    //<?xml version="1.0" encoding="UTF-16"?><root>
    //  <child><aaa/><ccc/></child>
    //</root>
}

String getNewLine ()

正在写出的 XML 中要使用的行尾字符序列。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var domImpl = builder.getDOMImplementation();

final var feature = domImpl.getFeature("LS", "3.0");
if (feature instanceof DOMImplementationLS ls) {
    final var serializer = ls.createLSSerializer();

    final var ret1 = serializer.getNewLine();
    System.out.println(Arrays.toString(ret1.getBytes())); // [10]
    System.out.println(ret1.equals("\n")); // true

    serializer.setNewLine("\r\n");

    final var ret2 = serializer.getNewLine();
    System.out.println(Arrays.toString(ret2.getBytes())); // [13, 10]
    System.out.println(ret2.equals("\r\n")); // true
}

void setFilter (LSSerializerFilter filter)

当应用程序提供过滤器时,序列化器将在序列化每个节点之前调用该过滤器。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var domImpl = builder.getDOMImplementation();

final var feature = domImpl.getFeature("LS", "3.0");
if (feature instanceof DOMImplementationLS ls) {

    final var xml = """
            <root>
              <child><aaa/><bbb/><ccc/></child>
            </root>
            """;

    final var input = ls.createLSInput();
    input.setStringData(xml);

    final var parser = ls.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
    final var document = parser.parse(input);

    final var serializer = ls.createLSSerializer();
    System.out.println(serializer.getFilter()); // null

    //<?xml version="1.0" encoding="UTF-16"?><root>
    //  <child><aaa/><bbb/><ccc/></child>
    //</root>
    System.out.println(serializer.writeToString(document));

    final var filter = new LSSerializerFilter() {
        @Override
        public short acceptNode(Node n) {
            System.out.println("acceptNode : " + n);

            if (n.getNodeName().equals("bbb")) {
                return NodeFilter.FILTER_REJECT;
            } else {
                return NodeFilter.FILTER_ACCEPT;
            }
        }

        @Override
        public int getWhatToShow() {
            return NodeFilter.SHOW_ELEMENT;
        }
    };

    serializer.setFilter(filter);
    System.out.println(filter == serializer.getFilter()); // true

    System.out.println("-- write start --");

    final var ret = serializer.writeToString(document);

    System.out.println("-- write end --");
    System.out.println(ret);

    // Result
    // ↓
    //-- write start --
    //acceptNode : [root: null]
    //acceptNode : [child: null]
    //acceptNode : [aaa: null]
    //acceptNode : [aaa: null]
    //acceptNode : [bbb: null]
    //acceptNode : [bbb: null]
    //acceptNode : [ccc: null]
    //acceptNode : [ccc: null]
    //acceptNode : [child: null]
    //acceptNode : [root: null]
    //-- write end --
    //<?xml version="1.0" encoding="UTF-16"?><root>
    //  <child><aaa/><ccc/></child>
    //</root>
}

void setNewLine (String newLine)

正在写出的 XML 中要使用的行尾字符序列。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var domImpl = builder.getDOMImplementation();

final var feature = domImpl.getFeature("LS", "3.0");
if (feature instanceof DOMImplementationLS ls) {
    final var serializer = ls.createLSSerializer();

    final var ret1 = serializer.getNewLine();
    System.out.println(Arrays.toString(ret1.getBytes())); // [10]
    System.out.println(ret1.equals("\n")); // true

    serializer.setNewLine("\r\n");

    final var ret2 = serializer.getNewLine();
    System.out.println(Arrays.toString(ret2.getBytes())); // [13, 10]
    System.out.println(ret2.equals("\r\n")); // true
}

boolean write (Node nodeArg, LSOutput destination)

按照上面 LSSerializer 接口的一般描述序列化指定的节点。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var domImpl = builder.getDOMImplementation();

final var feature = domImpl.getFeature("LS", "3.0");
if (feature instanceof DOMImplementationLS ls) {

    final var document = builder.newDocument();

    final var root = document.createElement("root");
    document.appendChild(root);

    final var text = document.createTextNode("abcd");
    root.appendChild(text);

    final var path = Path.of("R:", "java-work", "sample.xml");
    System.out.println(path); // R:\java-work\sample.xml

    try (final var writer = Files.newBufferedWriter(path)) {

        final var destination = ls.createLSOutput();
        destination.setCharacterStream(writer);

        final var serializer = ls.createLSSerializer();

        final var ret = serializer.write(document, destination);
        System.out.println(ret); // true
    }

    //<?xml version="1.0" encoding="UTF-8"?><root>abcd</root>
    System.out.println(Files.readString(path));
}

String writeToString (Node nodeArg)

按照上面 LSSerializer 接口的一般描述序列化指定的节点。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var domImpl = builder.getDOMImplementation();

final var feature = domImpl.getFeature("LS", "3.0");
if (feature instanceof DOMImplementationLS ls) {

    final var document = builder.newDocument();

    final var root = document.createElement("root");
    document.appendChild(root);

    final var text = document.createTextNode("abcd");
    root.appendChild(text);

    final var serializer = ls.createLSSerializer();
    final var str = serializer.writeToString(document);

    //<?xml version="1.0" encoding="UTF-16"?><root>abcd</root>
    System.out.println(str);
}

boolean writeToURI (Node nodeArg, String uri)

一种便捷方法,其作用就像使用未指定编码的 LSOutput 调用 LSSerializer.write 并将 LSOutput.systemId 设置为 uri 参数一样。 (机器翻译)

final var factory = DocumentBuilderFactory.newInstance();
final var builder = factory.newDocumentBuilder();
final var domImpl = builder.getDOMImplementation();

final var feature = domImpl.getFeature("LS", "3.0");
if (feature instanceof DOMImplementationLS ls) {

    final var document = builder.newDocument();

    final var root = document.createElement("root");
    document.appendChild(root);

    final var text = document.createTextNode("abcd");
    root.appendChild(text);

    final var path = Path.of("R:", "java-work", "sample.xml");
    System.out.println(path); // R:\java-work\sample.xml

    final var uri = path.toUri();
    System.out.println(uri); // file:///R:/java-work/sample.xml

    final var serializer = ls.createLSSerializer();

    final var ret = serializer.writeToURI(document, uri.toString());
    System.out.println(ret); // true

    //<?xml version="1.0" encoding="UTF-8"?><root>abcd</root>
    System.out.println(Files.readString(path));
}

相关文章

To top of page