Java : LSSerializer (XML) with Examples
LSSerializer (Java SE 22 & JDK 22) with Examples.
You will find code examples on most LSSerializer methods.
Summary
A LSSerializer provides an API for serializing (writing) a DOM document out into XML. The XML data is written to a string or an output stream. Any changes or fixups made during the serialization affect only the serialized data. The Document object and its children are never altered by the serialization operation.
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 ()
The DOMConfiguration object used by the LSSerializer when serializing a DOM node.
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 ()
When the application provides a filter, the serializer will call out to the filter before serializing each Node.
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 ()
The end-of-line sequence of characters to be used in the XML being written out.
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)
When the application provides a filter, the serializer will call out to the filter before serializing each Node.
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)
The end-of-line sequence of characters to be used in the XML being written out.
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)
Serialize the specified node as described above in the general description of the LSSerializer interface.
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)
Serialize the specified node as described above in the general description of the LSSerializer interface.
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)
A convenience method that acts as if LSSerializer.write was called with a LSOutput with no encoding specified and LSOutput.systemId set to the uri argument.
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));
}