Project

Profile

Help

Support #5059 » SaxonTransformerExample.java

Youssouf MHOMA, 2021-08-10 10:29

 
1
import org.w3c.dom.Document;
2
import org.w3c.dom.Element;
3

    
4
import javax.xml.parsers.DocumentBuilderFactory;
5
import javax.xml.parsers.ParserConfigurationException;
6
import javax.xml.transform.Transformer;
7
import javax.xml.transform.TransformerException;
8
import javax.xml.transform.TransformerFactory;
9
import javax.xml.transform.dom.DOMSource;
10
import javax.xml.transform.stream.StreamResult;
11
import java.io.StringWriter;
12

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

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

    
21
                Element titleEem = dom.createElement("title");
22
                titleEem.setTextContent("a_title");
23
                rootEle.appendChild(titleEem);
24

    
25
                dom.appendChild(rootEle);
26

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

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

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