Project

Profile

Help

Support #5059 » SaxonTransformerExample.java

Youssouf MHOMA, 2021-08-10 10:29

 
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 java.io.StringWriter;

public class SaxonTransformerExample {
public static void main(String[] args) throws ParserConfigurationException, TransformerException {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document dom = dbf.newDocumentBuilder().newDocument();

Element rootEle = dom.createElement("svg");
rootEle.setAttribute("xmlns", "http://www.w3.org/2000/svg");

Element titleEem = dom.createElement("title");
titleEem.setTextContent("a_title");
rootEle.appendChild(titleEem);

dom.appendChild(rootEle);

Transformer tr = TransformerFactory.newInstance().newTransformer();
StringWriter writer = new StringWriter();
tr.transform(new DOMSource(dom), new StreamResult(writer));

final String actual = writer.toString();
System.out.println("actual = " + actual);
final String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><svg xmlns=\"http://www.w3.org/2000/svg\"><title>a_title</title></svg>";
System.out.println("expected = " + expected);

if(expected.equals(actual)) {
System.out.println("working");
} else {
System.out.println("not working on 10.5. working on version 9.9.1-5");
System.out.println("no attribute on child is expected");
System.out.println("ps: if root hasn't \"xmlns\" attribute (line 19) = no attribute is added on child");
}
}
}
(1-1/2)