How to use XmlTest class of org.testng.xml package

Best Testng code snippet using org.testng.xml.XmlTest

Run Testng automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1diff --git a/src/main/java/org/testng/xml/XmlTest.java b/src/main/java/org/testng/xml/XmlTest.java
2index ec63e82..06abec1 100755
3--- a/src/main/java/org/testng/xml/XmlTest.java
4+++ b/src/main/java/org/testng/xml/XmlTest.java
5@@ -96,7 +96,7 @@
6 
7   // For YAML
8   public List<XmlPackage> getPackages() {
9-    return getPackages();
10+    return getXmlPackages();
11   }
12 
13   // For YAML
14
Full Screen
copy
1package com.r.india.testUnits;
2
3import java.util.ArrayList;
4import java.util.List;
5
6import org.testng.TestNG;
7import org.testng.xml.XmlClass;
8import org.testng.xml.XmlSuite;
9import org.testng.xml.XmlTest;
10
11public class mainClass {
12	
13	public static void main(String[] args) {
14		
15		XmlSuite xmlSuite = new XmlSuite();
16		xmlSuite.setName("r  Test");
17		xmlSuite.setParallel("false");
18		xmlSuite.setVerbose(1);
19		
20		int len = args.length;
21		if(len > 1)
22		{
23			String device_id = args[0];
24			String os_version = args[1];
25			String device_name = args[2];
26			String device_os = args[3];
27			
28			System.out.println(device_id);
29			System.out.println(os_version);
30			System.out.println(device_name);
31			System.out.println(device_os);
32			
33			XmlTest xmlTest = new XmlTest(xmlSuite);
34			xmlTest.setName("Browser/Mobile Test");
35			xmlTest.addParameter("device_id", device_id);
36			xmlTest.addParameter("os_version", os_version);
37			xmlTest.addParameter("device_name", device_name);
38			xmlTest.addParameter("device_os", device_os);
39			xmlTest.setPreserveOrder("true");
40			
41			XmlClass runner = new XmlClass(Runners.class);
42			
43			List<XmlClass> list = new ArrayList<XmlClass>();
44			list.add(runner);
45			
46			xmlTest.setXmlClasses(list);
47			
48		}else if(args[0].equalsIgnoreCase("web")){
49			
50			System.out.println(args[0]);
51			
52			XmlTest xmlTest = new XmlTest(xmlSuite);
53			xmlTest.setName("Browser/Mobile Test");
54			xmlTest.setPreserveOrder("true");
55			
56			XmlClass runner = new XmlClass(Runners.class);
57			
58			List<XmlClass> list = new ArrayList<XmlClass>();
59			list.add(runner);
60			
61			xmlTest.setXmlClasses(list);
62		}else{
63			System.out.println("\n"+"----------Please provide valid parameters---------");
64			System.out.println("\n"+"To test web application provide parameter as----> web");
65			System.out.println("\n"+"To test mobile application provide four parameters as----> device_id os_version device_name device_os \n");
66		}
67		
68		TestNG testNG = new TestNG();
69		
70		List<XmlSuite> suites = new ArrayList<XmlSuite>();
71		suites.add(xmlSuite);
72		
73		testNG.setXmlSuites(suites);
74		testNG.run();
75	}
76
77}
78
Full Screen
copy
1import org.testng.xml.XmlClass;
2import org.testng.xml.XmlSuite;
3import org.testng.xml.XmlTest;
4
5import java.util.ArrayList;
6import java.util.HashMap;
7import java.util.List;
8
9public class DynamicTest {
10
11    private HashMap<String, String> parameters;
12    private List<String> classes;
13    private String testName;
14
15    public HashMap<String, String> getParameters() {
16        return parameters;
17    }
18
19    public void setParameters(HashMap<String, String> parameters) {
20        this.parameters = parameters;
21    }
22
23    public List<String> getClasses() {
24        return classes;
25    }
26
27    public void setClasses(List<String> classes) {
28        this.classes = classes;
29    }
30
31    public String getTestName() {
32        return testName;
33    }
34
35    public void setTestName(String testName) {
36        this.testName = testName;
37    }
38
39    @Override
40    public String toString() {
41        return "DynamicTest{" +
42                "parameters=" + parameters +
43                ", classes=" + classes +
44                ", testName='" + testName + '\'' +
45                '}';
46    }
47
48
49    // Converts a list of strings with class names to a list of Xml Classes
50
51    public List<XmlClass> getXmlClasses(List<String> classes) {
52
53        List<XmlClass> xmlClasses = new ArrayList<XmlClass>();
54        for (String className : classes) {
55            xmlClasses.add(new XmlClass(className));
56        }
57        return xmlClasses;
58    }
59
60
61    // Returns an XmlTest
62
63    public XmlTest getXmlTest(XmlSuite suite) {
64
65        //Initiates an XmlTest associated with the suite
66        XmlTest xmlTest = new XmlTest(suite);
67
68        // Sets test name
69        xmlTest.setName(getTestName());
70
71        // Sets the list of test classes associated with this test
72        xmlTest.setClasses(getXmlClasses(getClasses()));
73
74        // Sets the parameters for this test
75        xmlTest.setParameters(getParameters());
76
77        return xmlTest;
78
79    }
80
81}
82
Full Screen
copy
1String leastPrettifiedXml = uglyXml.replaceAll("><", ">\n<");
2
Full Screen
copy
1def xml = "<tag><nested>hello</nested></tag>"
2def stringWriter = new StringWriter()
3def node = new XmlParser().parseText(xml);
4new XmlNodePrinter(new PrintWriter(stringWriter)).print(node)
5println stringWriter.toString()
6
Full Screen
copy
1  String xml = "<tag><nested>hello</nested></tag>";
2  StringWriter stringWriter = new StringWriter();
3  Node node = new XmlParser().parseText(xml);
4  new XmlNodePrinter(new PrintWriter(stringWriter)).print(node);
5  System.out.println(stringWriter.toString());
6
Full Screen
copy
1import org.apache.xml.security.c14n.CanonicalizationException;
2import org.apache.xml.security.c14n.Canonicalizer;
3import org.apache.xml.security.c14n.InvalidCanonicalizerException;
4import org.w3c.dom.Element;
5import org.w3c.dom.bootstrap.DOMImplementationRegistry;
6import org.w3c.dom.ls.DOMImplementationLS;
7import org.w3c.dom.ls.LSSerializer;
8import org.xml.sax.InputSource;
9import org.xml.sax.SAXException;
10
11import javax.xml.parsers.DocumentBuilderFactory;
12import javax.xml.parsers.ParserConfigurationException;
13import javax.xml.transform.TransformerException;
14import java.io.IOException;
15import java.io.StringReader;
16
17public class XmlUtils {
18    public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {
19        Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
20        byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());
21        return new String(canonXmlBytes);
22    }
23
24    public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {
25        InputSource src = new InputSource(new StringReader(input));
26        Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
27        Boolean keepDeclaration = input.startsWith("<?xml");
28        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
29        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
30        LSSerializer writer = impl.createLSSerializer();
31        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
32        writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
33        return writer.writeToString(document);
34    }
35}
36
Full Screen
copy
1private void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
2    String canonicalExpected = prettyFormat(toCanonicalXml(expected));
3    String canonicalActual = prettyFormat(toCanonicalXml(actual));
4    assertEquals(canonicalExpected, canonicalActual);
5}
6
Full Screen
copy
1public static class WhitespaceIgnoreFilter extends XMLFilterImpl
2{
3
4    @Override
5    public void ignorableWhitespace(char[] arg0,
6                                    int arg1,
7                                    int arg2) throws SAXException
8    {
9        //Ignore it then...
10    }
11
12    @Override
13    public void characters( char[] ch,
14                            int start,
15                            int length) throws SAXException
16    {
17        if (!new String(ch, start, length).trim().equals("")) 
18               super.characters(ch, start, length); 
19    }
20}
21
22public static String prettyXML(String logMsg, boolean allowBadlyFormedFragments) throws SAXException, IOException, TransformerException
23    {
24        TransformerFactory transFactory = TransformerFactory.newInstance();
25        transFactory.setAttribute("indent-number", new Integer(2));
26        Transformer transformer = transFactory.newTransformer();
27        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
28        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
29        StringWriter out = new StringWriter();
30        XMLReader masterParser = SAXHelper.getSAXParser(true);
31        XMLFilter parser = new WhitespaceIgnoreFilter();
32        parser.setParent(masterParser);
33
34        if(allowBadlyFormedFragments)
35        {
36            transformer.setErrorListener(new ErrorListener()
37            {
38                @Override
39                public void warning(TransformerException exception) throws TransformerException
40                {
41                }
42
43                @Override
44                public void fatalError(TransformerException exception) throws TransformerException
45                {
46                }
47
48                @Override
49                public void error(TransformerException exception) throws TransformerException
50                {
51                }
52            });
53        }
54
55        try
56        {
57            transformer.transform(new SAXSource(parser, new InputSource(new StringReader(logMsg))), new StreamResult(out));
58        }
59        catch (TransformerException e)
60        {
61            if(e.getCause() != null && e.getCause() instanceof SAXParseException)
62            {
63                if(!allowBadlyFormedFragments || !"XML document structures must start and end within the same entity.".equals(e.getCause().getMessage()))
64                {
65                    throw e;
66                }
67            }
68            else
69            {
70                throw e;
71            }
72        }
73        out.flush();
74        return out.toString();
75    }
76
Full Screen
copy
1public static String prettyPrintXml(String xmlStringToBeFormatted) {
2    String formattedXmlString = null;
3    try {
4        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
5        documentBuilderFactory.setValidating(true);
6        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
7        InputSource inputSource = new InputSource(new StringReader(xmlStringToBeFormatted));
8        Document document = documentBuilder.parse(inputSource);
9
10        Transformer transformer = TransformerFactory.newInstance().newTransformer();
11        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
12        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
13
14        StreamResult streamResult = new StreamResult(new StringWriter());
15        DOMSource dOMSource = new DOMSource(document);
16        transformer.transform(dOMSource, streamResult);
17        formattedXmlString = streamResult.getWriter().toString().trim();
18    } catch (Exception ex) {
19        StringWriter sw = new StringWriter();
20        ex.printStackTrace(new PrintWriter(sw));
21        System.err.println(sw.toString());
22    }
23    return formattedXmlString;
24}
25
Full Screen
copy
1public static String prettyPrintXMLAsString(String xmlString) {
2    /* Remove new lines */
3    final String LINE_BREAK = "\n";
4    xmlString = xmlString.replaceAll(LINE_BREAK, "");
5    StringBuffer prettyPrintXml = new StringBuffer();
6    /* Group the xml tags */
7    Pattern pattern = Pattern.compile("(<[^/][^>]+>)?([^<]*)(</[^>]+>)?(<[^/][^>]+/>)?");
8    Matcher matcher = pattern.matcher(xmlString);
9    int tabCount = 0;
10    while (matcher.find()) {
11        String str1 = (null == matcher.group(1) || "null".equals(matcher.group())) ? "" : matcher.group(1);
12        String str2 = (null == matcher.group(2) || "null".equals(matcher.group())) ? "" : matcher.group(2);
13        String str3 = (null == matcher.group(3) || "null".equals(matcher.group())) ? "" : matcher.group(3);
14        String str4 = (null == matcher.group(4) || "null".equals(matcher.group())) ? "" : matcher.group(4);
15
16        if (matcher.group() != null && !matcher.group().trim().equals("")) {
17            printTabs(tabCount, prettyPrintXml);
18            if (!str1.equals("") && str3.equals("")) {
19                ++tabCount;
20            }
21            if (str1.equals("") && !str3.equals("")) {
22                --tabCount;
23                prettyPrintXml.deleteCharAt(prettyPrintXml.length() - 1);
24            }
25
26            prettyPrintXml.append(str1);
27            prettyPrintXml.append(str2);
28            prettyPrintXml.append(str3);
29            if (!str4.equals("")) {
30                prettyPrintXml.append(LINE_BREAK);
31                printTabs(tabCount, prettyPrintXml);
32                prettyPrintXml.append(str4);
33            }
34            prettyPrintXml.append(LINE_BREAK);
35        }
36    }
37    return prettyPrintXml.toString();
38}
39
40private static void printTabs(int count, StringBuffer stringBuffer) {
41    for (int i = 0; i < count; i++) {
42        stringBuffer.append("\t");
43    }
44}
45
46public static void main(String[] args) {
47    String x = new String(
48            "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode>soap:Client</faultcode><faultstring>INVALID_MESSAGE</faultstring><detail><ns3:XcbSoapFault xmlns=\"\" xmlns:ns3=\"http://www.someapp.eu/xcb/types/xcb/v1\"><CauseCode>20007</CauseCode><CauseText>INVALID_MESSAGE</CauseText><DebugInfo>Problems creating SAAJ object model</DebugInfo></ns3:XcbSoapFault></detail></soap:Fault></soap:Body></soap:Envelope>");
49    System.out.println(prettyPrintXMLAsString(x));
50}
51
Full Screen
copy
1<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
2  <soap:Body>
3    <soap:Fault>
4        <faultcode>soap:Client</faultcode>
5        <faultstring>INVALID_MESSAGE</faultstring>
6        <detail>
7            <ns3:XcbSoapFault xmlns="" xmlns:ns3="http://www.someapp.eu/xcb/types/xcb/v1">
8                <CauseCode>20007</CauseCode>
9                <CauseText>INVALID_MESSAGE</CauseText>
10                <DebugInfo>Problems creating SAAJ object model</DebugInfo>
11            </ns3:XcbSoapFault>
12        </detail>
13    </soap:Fault>
14  </soap:Body>
15</soap:Envelope>
16
Full Screen
copy
1Tidy t = new Tidy();
2t.setIndentContent(true);
3Document d = t.parseDOM(
4    new ByteArrayInputStream("HTML goes here", null);
5
6OutputStream out = new ByteArrayOutputStream();
7t.pprint(d, out);
8String html = out.toString();
9
Full Screen
copy
1// construct lightweight, threadsafe, instance
2PrettyPrinter prettyPrinter = PrettyPrinterBuilder.newPrettyPrinter().build();
3
4StringBuilder buffer = new StringBuilder();
5String xml = ..; // also works with char[] or Reader
6
7if(prettyPrinter.process(xml, buffer)) {
8     // valid XML, print buffer
9} else {
10     // invalid XML, print xml
11}
12
Full Screen
copy
1PrettyPrinter prettyPrinter = PrettyPrinterBuilder.newPrettyPrinter().ignoreWhitespace().build();
2
Full Screen
copy
1import java.io.StringReader;
2import org.jdom2.input.SAXBuilder;
3import org.jdom2.output.Format;
4import org.jdom2.output.XMLOutputter;
5
6String prettyXml = new XMLOutputter(Format.getPrettyFormat()).
7                         outputString(new SAXBuilder().build(new StringReader(uglyXml)));
8
Full Screen
copy
1import java.io.StringWriter;
2import org.dom4j.DocumentHelper;
3import org.dom4j.io.OutputFormat;
4import org.dom4j.io.XMLWriter;
5
6**
7 * Pretty Print XML String
8 * 
9 * @param inputXmlString
10 * @return
11 */
12public static String prettyPrintXml(String xml) {
13
14    final StringWriter sw;
15
16    try {
17        final OutputFormat format = OutputFormat.createPrettyPrint();
18        final org.dom4j.Document document = DocumentHelper.parseText(xml);
19        sw = new StringWriter();
20        final XMLWriter writer = new XMLWriter(sw, format);
21        writer.write(document);
22    }
23    catch (Exception e) {
24        throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
25    }
26    return sw.toString();
27}
28
Full Screen
copy
1public String prettyPrint(String xml) {
2            if (xml == null || xml.trim().length() == 0) return "";
3
4            int stack = 0;
5            StringBuilder pretty = new StringBuilder();
6            String[] rows = xml.trim().replaceAll(">", ">\n").replaceAll("<", "\n<").split("\n");
7
8            for (int i = 0; i < rows.length; i++) {
9                    if (rows[i] == null || rows[i].trim().length() == 0) continue;
10
11                    String row = rows[i].trim();
12                    if (row.startsWith("<?")) {
13                            // xml version tag
14                            pretty.append(row + "\n");
15                    } else if (row.startsWith("</")) {
16                            // closing tag
17                            String indent = repeatString("    ", --stack);
18                            pretty.append(indent + row + "\n");
19                    } else if (row.startsWith("<")) {
20                            // starting tag
21                            String indent = repeatString("    ", stack++);
22                            pretty.append(indent + row + "\n");
23                    } else {
24                            // tag data
25                            String indent = repeatString("    ", stack);
26                            pretty.append(indent + row + "\n");
27                    }
28            }
29
30            return pretty.toString().trim();
31    }
32
Full Screen
copy
1    public static void main(String[] args) throws Exception {
2    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
3    dbf.setValidating(false);
4    DocumentBuilder db = dbf.newDocumentBuilder();
5    Document doc = db.parse(new FileInputStream(new File("C:/Users/xyz.xml")));
6    prettyPrint(doc);
7
8}
9
10private static String prettyPrint(Document document)
11        throws TransformerException {
12    TransformerFactory transformerFactory = TransformerFactory
13            .newInstance();
14    Transformer transformer = transformerFactory.newTransformer();
15    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
16    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
17    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
18    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
19    DOMSource source = new DOMSource(document);
20    StringWriter strWriter = new StringWriter();
21    StreamResult result = new StreamResult(strWriter);transformer.transform(source, result);
22    System.out.println(strWriter.getBuffer().toString());
23
24    return strWriter.getBuffer().toString();
25
26}
27
Full Screen
copy
1import javax.xml.transform.OutputKeys;
2import javax.xml.transform.Source;
3import javax.xml.transform.Transformer;
4import javax.xml.transform.TransformerFactory;
5import javax.xml.transform.stream.StreamResult;
6import javax.xml.transform.stream.StreamSource;
7
8String formattedXml1 = prettyFormat("<root><child>aaa</child><child/></root>");
9
10public static String prettyFormat(String input) {
11    return prettyFormat(input, "2");
12}
13
14public static String prettyFormat(String input, String indent) {
15    Source xmlInput = new StreamSource(new StringReader(input));
16    StringWriter stringWriter = new StringWriter();
17    try {
18        TransformerFactory transformerFactory = TransformerFactory.newInstance();
19        Transformer transformer = transformerFactory.newTransformer();
20        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
21        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", indent);
22        transformer.transform(xmlInput, new StreamResult(stringWriter));
23
24        String pretty = stringWriter.toString();
25        pretty = pretty.replace("\r\n", "\n");
26        return pretty;              
27    } catch (Exception e) {
28        throw new RuntimeException(e);
29    }
30}
31
Full Screen
copy
1    String xml = "<root>" +
2             "\n   " +
3             "\n<name>Coco Puff</name>" +
4             "\n        <total>10</total>    </root>";
5
6try {
7    Document document = DocumentBuilderFactory.newInstance()
8            .newDocumentBuilder()
9            .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
10
11    XPath xPath = XPathFactory.newInstance().newXPath();
12    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
13                                                  document,
14                                                  XPathConstants.NODESET);
15
16    for (int i = 0; i < nodeList.getLength(); ++i) {
17        Node node = nodeList.item(i);
18        node.getParentNode().removeChild(node);
19    }
20
21    Transformer transformer = TransformerFactory.newInstance().newTransformer();
22    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
23    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
24    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
25    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
26
27    StringWriter stringWriter = new StringWriter();
28    StreamResult streamResult = new StreamResult(stringWriter);
29
30    transformer.transform(new DOMSource(document), streamResult);
31
32    System.out.println(stringWriter.toString());
33}
34catch (Exception e) {
35    e.printStackTrace();
36}
37
Full Screen
copy
1DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
2DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
3LSSerializer writer = impl.createLSSerializer();
4writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
5LSOutput output = impl.createLSOutput();
6ByteArrayOutputStream out = new ByteArrayOutputStream();
7output.setByteStream(out);
8writer.write(document, output);
9String xmlStr = new String(out.toByteArray());
10
Full Screen
copy
1public static String getPrettyXml(String xml) {
2    if (xml == null || xml.trim().length() == 0) return "";
3
4    int stack = 0;
5    StringBuilder pretty = new StringBuilder();
6    String[] rows = xml.trim().replaceAll(">", ">\n").replaceAll("<", "\n<").split("\n");
7
8    for (int i = 0; i < rows.length; i++) {
9        if (rows[i] == null || rows[i].trim().length() == 0) continue;
10
11        String row = rows[i].trim();
12        if (row.startsWith("<?")) {
13            pretty.append(row + "\n");
14        } else if (row.startsWith("</")) {
15            String indent = repeatString(--stack);
16            pretty.append(indent + row + "\n");
17        } else if (row.startsWith("<") && row.endsWith("/>") == false) {
18            String indent = repeatString(stack++);
19            pretty.append(indent + row + "\n");
20            if (row.endsWith("]]>")) stack--;
21        } else {
22            String indent = repeatString(stack);
23            pretty.append(indent + row + "\n");
24        }
25    }
26
27    return pretty.toString().trim();
28}
29
30private static String repeatString(int stack) {
31     StringBuilder indent = new StringBuilder();
32     for (int i = 0; i < stack; i++) {
33        indent.append(" ");
34     }
35     return indent.toString();
36} 
37
Full Screen
copy
1import xml._
2val xml = XML.loadString("<tag><nested>hello</nested></tag>")
3val formatted = new PrettyPrinter(150, 2).format(xml)
4println(formatted)
5
Full Screen
copy
1import scala.xml.*;
2
3public class FormatXML {
4    public static void main(String[] args) {
5        String unformattedXml = "<tag><nested>hello</nested></tag>";
6        PrettyPrinter pp = new PrettyPrinter(150, 3);
7        String formatted = pp.format(XML.loadString(unformattedXml), TopScope$.MODULE$);
8        System.out.println(formatted);
9    }
10}
11
Full Screen
copy
1transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "8");
2
Full Screen
copy
1import nu.xom.*;
2import java.io.*;
3
4[...]
5
6public static String format(String xml) throws ParsingException, IOException {
7    ByteArrayOutputStream out = new ByteArrayOutputStream();
8    Serializer serializer = new Serializer(out);
9    serializer.setIndent(4);  // or whatever you like
10    serializer.write(new Builder().build(xml, ""));
11    return out.toString("UTF-8");
12}
13
Full Screen
copy
1/**
2 * XML utils, including formatting.
3 */
4public class XmlUtils
5{
6  private static XmlFormatter formatter = new XmlFormatter(2, 80);
7
8  public static String formatXml(String s)
9  {
10    return formatter.format(s, 0);
11  }
12
13  public static String formatXml(String s, int initialIndent)
14  {
15    return formatter.format(s, initialIndent);
16  }
17
18  private static class XmlFormatter
19  {
20    private int indentNumChars;
21    private int lineLength;
22    private boolean singleLine;
23
24    public XmlFormatter(int indentNumChars, int lineLength)
25    {
26      this.indentNumChars = indentNumChars;
27      this.lineLength = lineLength;
28    }
29
30    public synchronized String format(String s, int initialIndent)
31    {
32      int indent = initialIndent;
33      StringBuilder sb = new StringBuilder();
34      for (int i = 0; i < s.length(); i++)
35      {
36        char currentChar = s.charAt(i);
37        if (currentChar == '<')
38        {
39          char nextChar = s.charAt(i + 1);
40          if (nextChar == '/')
41            indent -= indentNumChars;
42          if (!singleLine)   // Don't indent before closing element if we're creating opening and closing elements on a single line.
43            sb.append(buildWhitespace(indent));
44          if (nextChar != '?' && nextChar != '!' && nextChar != '/')
45            indent += indentNumChars;
46          singleLine = false;  // Reset flag.
47        }
48        sb.append(currentChar);
49        if (currentChar == '>')
50        {
51          if (s.charAt(i - 1) == '/')
52          {
53            indent -= indentNumChars;
54            sb.append("\n");
55          }
56          else
57          {
58            int nextStartElementPos = s.indexOf('<', i);
59            if (nextStartElementPos > i + 1)
60            {
61              String textBetweenElements = s.substring(i + 1, nextStartElementPos);
62
63              // If the space between elements is solely newlines, let them through to preserve additional newlines in source document.
64              if (textBetweenElements.replaceAll("\n", "").length() == 0)
65              {
66                sb.append(textBetweenElements + "\n");
67              }
68              // Put tags and text on a single line if the text is short.
69              else if (textBetweenElements.length() <= lineLength * 0.5)
70              {
71                sb.append(textBetweenElements);
72                singleLine = true;
73              }
74              // For larger amounts of text, wrap lines to a maximum line length.
75              else
76              {
77                sb.append("\n" + lineWrap(textBetweenElements, lineLength, indent, null) + "\n");
78              }
79              i = nextStartElementPos - 1;
80            }
81            else
82            {
83              sb.append("\n");
84            }
85          }
86        }
87      }
88      return sb.toString();
89    }
90  }
91
92  private static String buildWhitespace(int numChars)
93  {
94    StringBuilder sb = new StringBuilder();
95    for (int i = 0; i < numChars; i++)
96      sb.append(" ");
97    return sb.toString();
98  }
99
100  /**
101   * Wraps the supplied text to the specified line length.
102   * @lineLength the maximum length of each line in the returned string (not including indent if specified).
103   * @indent optional number of whitespace characters to prepend to each line before the text.
104   * @linePrefix optional string to append to the indent (before the text).
105   * @returns the supplied text wrapped so that no line exceeds the specified line length + indent, optionally with
106   * indent and prefix applied to each line.
107   */
108  private static String lineWrap(String s, int lineLength, Integer indent, String linePrefix)
109  {
110    if (s == null)
111      return null;
112
113    StringBuilder sb = new StringBuilder();
114    int lineStartPos = 0;
115    int lineEndPos;
116    boolean firstLine = true;
117    while(lineStartPos < s.length())
118    {
119      if (!firstLine)
120        sb.append("\n");
121      else
122        firstLine = false;
123
124      if (lineStartPos + lineLength > s.length())
125        lineEndPos = s.length() - 1;
126      else
127      {
128        lineEndPos = lineStartPos + lineLength - 1;
129        while (lineEndPos > lineStartPos && (s.charAt(lineEndPos) != ' ' && s.charAt(lineEndPos) != '\t'))
130          lineEndPos--;
131      }
132      sb.append(buildWhitespace(indent));
133      if (linePrefix != null)
134        sb.append(linePrefix);
135
136      sb.append(s.substring(lineStartPos, lineEndPos + 1));
137      lineStartPos = lineEndPos + 1;
138    }
139    return sb.toString();
140  }
141
142  // other utils removed for brevity
143}
144
Full Screen
copy
1public static final Element createDOM(String strXML) 
2    throws ParserConfigurationException, SAXException, IOException {
3
4    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
5    dbf.setValidating(true);
6    DocumentBuilder db = dbf.newDocumentBuilder();
7    InputSource sourceXML = new InputSource(new StringReader(strXML));
8    Document xmlDoc = db.parse(sourceXML);
9    Element e = xmlDoc.getDocumentElement();
10    e.normalize();
11    return e;
12}
13
14public static final void prettyPrint(Node xml, OutputStream out)
15    throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException {
16    Transformer tf = TransformerFactory.newInstance().newTransformer();
17    tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
18    tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
19    tf.setOutputProperty(OutputKeys.INDENT, "yes");
20    tf.transform(new DOMSource(xml), new StreamResult(out));
21}
22
Full Screen
copy
1import org.dom4j.Document;  
2import org.dom4j.DocumentHelper;  
3import org.dom4j.io.OutputFormat;  
4import org.dom4j.io.XMLWriter;
5
Full Screen
copy
1String xml = "<your xml='here'/>";  
2Document doc = DocumentHelper.parseText(xml);  
3StringWriter sw = new StringWriter();  
4OutputFormat format = OutputFormat.createPrettyPrint();  
5XMLWriter xw = new XMLWriter(sw, format);  
6xw.write(doc);  
7String result = sw.toString();
8
Full Screen
copy
1public String prettyPrint(final String xml){  
2
3    if (StringUtils.isBlank(xml)) {
4        throw new RuntimeException("xml was null or blank in prettyPrint()");
5    }
6
7    final StringWriter sw;
8
9    try {
10        final OutputFormat format = OutputFormat.createPrettyPrint();
11        final org.dom4j.Document document = DocumentHelper.parseText(xml);
12        sw = new StringWriter();
13        final XMLWriter writer = new XMLWriter(sw, format);
14        writer.write(document);
15    }
16    catch (Exception e) {
17        throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
18    }
19    return sw.toString();
20}
21
Full Screen
copy
1package com.test;
2
3import java.io.ByteArrayInputStream;
4import java.io.ByteArrayOutputStream;
5
6import javax.xml.transform.OutputKeys;
7import javax.xml.transform.Source;
8import javax.xml.transform.Transformer;
9import javax.xml.transform.sax.SAXSource;
10import javax.xml.transform.sax.SAXTransformerFactory;
11import javax.xml.transform.stream.StreamResult;
12
13import org.xml.sax.InputSource;
14
15public class XmlTest {
16    public static void main(String[] args) {
17        XmlTest t = new XmlTest();
18        System.out.println(t.formatXml("<a><b><c/><d>text D</d><e value='0'/></b></a>"));
19    }
20
21    public String formatXml(String xml){
22        try{
23            Transformer serializer= SAXTransformerFactory.newInstance().newTransformer();
24            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
25            //serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
26            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
27            //serializer.setOutputProperty("{http://xml.customer.org/xslt}indent-amount", "2");
28            Source xmlSource=new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
29            StreamResult res =  new StreamResult(new ByteArrayOutputStream());            
30            serializer.transform(xmlSource, res);
31            return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
32        }catch(Exception e){
33            //TODO log error
34            return xml;
35        }
36    }
37
38}
39
Full Screen
copy
1import org.w3c.dom.Node;
2import org.w3c.dom.bootstrap.DOMImplementationRegistry;
3import org.w3c.dom.ls.DOMImplementationLS;
4import org.w3c.dom.ls.LSSerializer;
5import org.xml.sax.InputSource;
6
7import javax.xml.parsers.DocumentBuilderFactory;
8import java.io.StringReader;
9
10/**
11 * Pretty-prints xml, supplied as a string.
12 * <p/>
13 * eg.
14 * <code>
15 * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
16 * </code>
17 */
18public class XmlFormatter {
19
20    public String format(String xml) {
21
22        try {
23            final InputSource src = new InputSource(new StringReader(xml));
24            final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
25            final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
26
27        //May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
28
29
30            final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
31            final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
32            final LSSerializer writer = impl.createLSSerializer();
33
34            writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
35            writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.
36
37            return writer.writeToString(document);
38        } catch (Exception e) {
39            throw new RuntimeException(e);
40        }
41    }
42
43    public static void main(String[] args) {
44        String unformattedXml =
45                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
46                        "        xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
47                        "        xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
48                        "    <Query>\n" +
49                        "        <query:CategorySchemeWhere>\n" +
50                        "   \t\t\t\t\t         <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
51                        "        </query:CategorySchemeWhere>\n" +
52                        "    </Query>\n\n\n\n\n" +
53                        "</QueryMessage>";
54
55        System.out.println(new XmlFormatter().format(unformattedXml));
56    }
57}
58
Full Screen
copy
1public static String prettyFormat(String input, int indent) {
2    try {
3        Source xmlInput = new StreamSource(new StringReader(input));
4        StringWriter stringWriter = new StringWriter();
5        StreamResult xmlOutput = new StreamResult(stringWriter);
6        TransformerFactory transformerFactory = TransformerFactory.newInstance();
7        transformerFactory.setAttribute("indent-number", indent);
8        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
9        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
10        Transformer transformer = transformerFactory.newTransformer(); 
11        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
12        transformer.transform(xmlInput, xmlOutput);
13        return xmlOutput.getWriter().toString();
14    } catch (Exception e) {
15        throw new RuntimeException(e); // simple exception handling, please review it
16    }
17}
18
19public static String prettyFormat(String input) {
20    return prettyFormat(input, 2);
21}
22
Full Screen
copy
1prettyFormat("<root><child>aaa</child><child/></root>");
2
Full Screen
copy
1<?xml version="1.0" encoding="UTF-8"?>
2<root>
3  <child>aaa</child>
4  <child/>
5</root>
6
Full Screen
copy
1package ecb.sdw.pretty;
2
3import org.apache.xml.serialize.OutputFormat;
4import org.apache.xml.serialize.XMLSerializer;
5import org.w3c.dom.Document;
6import org.xml.sax.InputSource;
7import org.xml.sax.SAXException;
8
9import javax.xml.parsers.DocumentBuilder;
10import javax.xml.parsers.DocumentBuilderFactory;
11import javax.xml.parsers.ParserConfigurationException;
12import java.io.IOException;
13import java.io.StringReader;
14import java.io.StringWriter;
15import java.io.Writer;
16
17/**
18 * Pretty-prints xml, supplied as a string.
19 * <p/>
20 * eg.
21 * <code>
22 * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
23 * </code>
24 */
25public class XmlFormatter {
26
27    public XmlFormatter() {
28    }
29
30    public String format(String unformattedXml) {
31        try {
32            final Document document = parseXmlFile(unformattedXml);
33
34            OutputFormat format = new OutputFormat(document);
35            format.setLineWidth(65);
36            format.setIndenting(true);
37            format.setIndent(2);
38            Writer out = new StringWriter();
39            XMLSerializer serializer = new XMLSerializer(out, format);
40            serializer.serialize(document);
41
42            return out.toString();
43        } catch (IOException e) {
44            throw new RuntimeException(e);
45        }
46    }
47
48    private Document parseXmlFile(String in) {
49        try {
50            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
51            DocumentBuilder db = dbf.newDocumentBuilder();
52            InputSource is = new InputSource(new StringReader(in));
53            return db.parse(is);
54        } catch (ParserConfigurationException e) {
55            throw new RuntimeException(e);
56        } catch (SAXException e) {
57            throw new RuntimeException(e);
58        } catch (IOException e) {
59            throw new RuntimeException(e);
60        }
61    }
62
63    public static void main(String[] args) {
64        String unformattedXml =
65                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
66                        "        xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
67                        "        xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
68                        "    <Query>\n" +
69                        "        <query:CategorySchemeWhere>\n" +
70                        "   \t\t\t\t\t         <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
71                        "        </query:CategorySchemeWhere>\n" +
72                        "    </Query>\n\n\n\n\n" +
73                        "</QueryMessage>";
74
75        System.out.println(new XmlFormatter().format(unformattedXml));
76    }
77
78}
79
Full Screen
copy
1Transformer transformer = TransformerFactory.newInstance().newTransformer();
2transformer.setOutputProperty(OutputKeys.INDENT, "yes");
3transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
4// initialize StreamResult with File object to save to file
5StreamResult result = new StreamResult(new StringWriter());
6DOMSource source = new DOMSource(doc);
7transformer.transform(source, result);
8String xmlString = result.getWriter().toString();
9System.out.println(xmlString);
10
Full Screen
copy
1            // read in the xml document
2            org.xml.sax.InputSource is=new org.xml.sax.InputSource();
3            is.setByteStream(instream);
4            if (encoding!=null) {
5                is.setEncoding(encoding);
6                if (Debug.CORE)
7                    Debug.log("setting XML encoding to - "+is.getEncoding());
8            }   
9
Full Screen
copy
1/**
2 * LineNumber Handler
3 * @author wf
4 *
5 */
6public static class LineNumberHandler extends DefaultHandler {
7
8final Stack<Element> elementStack = new Stack<Element>();
9final StringBuilder textBuffer = new StringBuilder();
10private Locator locator;
11private Document doc;
12
13/**
14 * create a line number Handler for the given document
15 * @param doc
16 */
17public LineNumberHandler(Document doc) {
18  this.doc=doc;
19}
20
21@Override
22public void setDocumentLocator(final Locator locator) {
23  this.locator = locator; // Save the locator, so that it can be used
24                          // later for line tracking when traversing
25                          // nodes.
26}
27
28@Override
29public void startElement(final String uri, final String localName,
30    final String qName, final Attributes attributes) throws SAXException {
31  addTextIfNeeded();
32  final Element el = doc.createElement(qName);
33  for (int i = 0; i < attributes.getLength(); i++) {
34    el.setAttribute(attributes.getQName(i), attributes.getValue(i));
35  }
36  el.setUserData(LINE_NUMBER_KEY_NAME,
37      String.valueOf(this.locator.getLineNumber()), null);
38  elementStack.push(el);
39}
40
41@Override
42public void endElement(final String uri, final String localName,
43    final String qName) {
44  addTextIfNeeded();
45  final Element closedEl = elementStack.pop();
46  if (elementStack.isEmpty()) { // Is this the root element?
47    doc.appendChild(closedEl);
48  } else {
49    final Element parentEl = elementStack.peek();
50    parentEl.appendChild(closedEl);
51  }
52}
53
54@Override
55public void characters(final char ch[], final int start, final int length)
56    throws SAXException {
57  textBuffer.append(ch, start, length);
58}
59
60// Outputs text accumulated under the current node
61private void addTextIfNeeded() {
62  if (textBuffer.length() > 0) {
63    final Element el = elementStack.peek();
64    final Node textNode = doc.createTextNode(textBuffer.toString());
65    el.appendChild(textNode);
66    textBuffer.delete(0, textBuffer.length());
67  }
68}
69
Full Screen
copy
1public class PositionalXMLReader {
2  final static String LINE_NUMBER_KEY_NAME = "lineNumber";
3 /**
4  * read a document from the given input strem
5  * 
6  * @param is
7  *          - the input stream
8  * @return - the Document
9  * @throws IOException
10  * @throws SAXException
11  */
12public static Document readXML(final InputStream is)
13  throws IOException, SAXException {
14  final Document doc;
15  SAXParser parser;
16    try {
17      final SAXParserFactory factory = SAXParserFactory.newInstance();
18      parser = factory.newSAXParser();
19      final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
20      .newInstance();
21      final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
22      doc = docBuilder.newDocument();
23    } catch (final ParserConfigurationException e) {
24      throw new RuntimeException("Can't create SAX parser / DOM builder.", e);
25    }
26    LineNumberHandler handler = new LineNumberHandler(doc);
27    parser.parse(is, handler);
28
29    return doc;
30  }
31}
32
Full Screen
copy
1package com.bitplan.common.impl;
2
3import static org.junit.Assert.assertEquals;
4
5import java.io.ByteArrayInputStream;
6import java.io.InputStream;
7
8import org.junit.Test;
9import org.w3c.dom.Document;
10import org.w3c.dom.Node;
11
12import com.bitplan.bobase.PositionalXMLReader;
13
14public class TestXMLWithLineNumbers {
15
16  /**
17   * get an Example XML Stream
18   * @return the example stream
19   */
20  public InputStream getExampleXMLStream() {
21    String xmlString = "<foo>\n" + "    <bar>\n"
22        + "        <moo>Hello World!</moo>\n" + "    </bar>\n" + "</foo>";
23
24    InputStream is = new ByteArrayInputStream(xmlString.getBytes());
25    return is;
26  }
27
28  @Test
29  public void testXMLWithLineNumbers() throws Exception {
30    InputStream is = this.getExampleXMLStream();
31    Document doc = PositionalXMLReader.readXML(is);
32    is.close();
33
34    Node node = doc.getElementsByTagName("moo").item(0);
35    assertEquals("3", node.getUserData("lineNumber"));
36  }  
37}
38
Full Screen
copy
1<Element></Element>
2
Full Screen
copy
1<Element
2   attribute1="X"
3   attribute2="Y">
4</Element>
5
Full Screen
copy
1// XmlTest.java
2
3import java.io.ByteArrayInputStream;
4import java.io.InputStream;
5
6import org.w3c.dom.Document;
7import org.w3c.dom.Node;
8
9public class XmlTest {
10    public static void main(final String[] args) throws Exception {
11
12        String xmlString = "<foo>\n"
13                         + "    <bar>\n"
14                         + "        <moo>Hello World!</moo>\n"
15                         + "    </bar>\n"
16                         + "</foo>";
17
18        InputStream is = new ByteArrayInputStream(xmlString.getBytes());
19        Document doc = PositionalXMLReader.readXML(is);
20        is.close();
21
22        Node node = doc.getElementsByTagName("moo").item(0);
23
24        System.out.println("Line number: " + node.getUserData("lineNumber"));
25    }
26}
27
Full Screen
copy
1// PositionalXMLReader.java
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.util.Stack;
6
7import javax.xml.parsers.DocumentBuilder;
8import javax.xml.parsers.DocumentBuilderFactory;
9import javax.xml.parsers.ParserConfigurationException;
10import javax.xml.parsers.SAXParser;
11import javax.xml.parsers.SAXParserFactory;
12
13import org.w3c.dom.Document;
14import org.w3c.dom.Element;
15import org.w3c.dom.Node;
16import org.xml.sax.Attributes;
17import org.xml.sax.Locator;
18import org.xml.sax.SAXException;
19import org.xml.sax.helpers.DefaultHandler;
20
21public class PositionalXMLReader {
22    final static String LINE_NUMBER_KEY_NAME = "lineNumber";
23
24    public static Document readXML(final InputStream is) throws IOException, SAXException {
25        final Document doc;
26        SAXParser parser;
27        try {
28            final SAXParserFactory factory = SAXParserFactory.newInstance();
29            parser = factory.newSAXParser();
30            final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
31            final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
32            doc = docBuilder.newDocument();
33        } catch (final ParserConfigurationException e) {
34            throw new RuntimeException("Can't create SAX parser / DOM builder.", e);
35        }
36
37        final Stack<Element> elementStack = new Stack<Element>();
38        final StringBuilder textBuffer = new StringBuilder();
39        final DefaultHandler handler = new DefaultHandler() {
40            private Locator locator;
41
42            @Override
43            public void setDocumentLocator(final Locator locator) {
44                this.locator = locator; // Save the locator, so that it can be used later for line tracking when traversing nodes.
45            }
46
47            @Override
48            public void startElement(final String uri, final String localName, final String qName, final Attributes attributes)
49                    throws SAXException {
50                addTextIfNeeded();
51                final Element el = doc.createElement(qName);
52                for (int i = 0; i < attributes.getLength(); i++) {
53                    el.setAttribute(attributes.getQName(i), attributes.getValue(i));
54                }
55                el.setUserData(LINE_NUMBER_KEY_NAME, String.valueOf(this.locator.getLineNumber()), null);
56                elementStack.push(el);
57            }
58
59            @Override
60            public void endElement(final String uri, final String localName, final String qName) {
61                addTextIfNeeded();
62                final Element closedEl = elementStack.pop();
63                if (elementStack.isEmpty()) { // Is this the root element?
64                    doc.appendChild(closedEl);
65                } else {
66                    final Element parentEl = elementStack.peek();
67                    parentEl.appendChild(closedEl);
68                }
69            }
70
71            @Override
72            public void characters(final char ch[], final int start, final int length) throws SAXException {
73                textBuffer.append(ch, start, length);
74            }
75
76            // Outputs text accumulated under the current node
77            private void addTextIfNeeded() {
78                if (textBuffer.length() > 0) {
79                    final Element el = elementStack.peek();
80                    final Node textNode = doc.createTextNode(textBuffer.toString());
81                    el.appendChild(textNode);
82                    textBuffer.delete(0, textBuffer.length());
83                }
84            }
85        };
86        parser.parse(is, handler);
87
88        return doc;
89    }
90}
91
Full Screen
copy
1<?xml version="1.0" encoding="UTF-8"?>
2<schema xmlns="http://www.w3.org/2001/XMLSchema" 
3targetNamespace="http://www.example.org/Sport"
4xmlns:tns="http://www.example.org/Sport" 
5elementFormDefault="qualified"
6xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" 
7jaxb:version="2.0">
8
9<complexType name="sportType">
10    <attribute name="type" type="string" />
11    <attribute name="gender" type="string" />
12</complexType>
13
14<element name="sports">
15    <complexType>
16        <sequence>
17            <element name="sport" minOccurs="0" maxOccurs="unbounded"
18                type="tns:sportType" />
19        </sequence>
20    </complexType>
21</element>
22
Full Screen
copy
1package org.example.sport; 
2
3import javax.xml.bind.annotation.XmlAccessType;
4import javax.xml.bind.annotation.XmlAccessorType;
5import javax.xml.bind.annotation.XmlAttribute;
6import javax.xml.bind.annotation.XmlType;
7
8
9@XmlAccessorType(XmlAccessType.FIELD)
10@XmlType(name = "sportType")
11public class SportType {
12
13    @XmlAttribute
14    protected String type;
15    @XmlAttribute
16    protected String gender;
17
18    public String getType() {
19        return type;
20    }
21
22
23    public void setType(String value) {
24        this.type = value;
25    }
26
27    public String getGender() {
28        return gender;
29    }
30
31    public void setGender(String value) {
32        this.gender = value;
33    }
34
35}
36
Full Screen
copy
1package org.example.sport;
2
3import java.util.ArrayList;
4import java.util.List;
5import javax.xml.bind.annotation.XmlAccessType;
6import javax.xml.bind.annotation.XmlAccessorType;
7import javax.xml.bind.annotation.XmlRootElement;
8import javax.xml.bind.annotation.XmlType;
9
10
11@XmlAccessorType(XmlAccessType.FIELD)
12@XmlType(name = "", propOrder = {
13        "sport"
14})
15@XmlRootElement(name = "sports")
16public class Sports {
17
18    protected List<SportType> sport;
19
20    public List<SportType> getSport() {
21        if (sport == null) {
22            sport = new ArrayList<SportType>();
23        }
24        return this.sport;
25    }
26
27}
28
Full Screen
copy
1public class XmlTest {
2
3    private static final Logger log = LoggerFactory.getLogger(XmlTest.class);
4
5    @Test
6    public void createDefaultBook() throws JAXBException {
7        JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
8        Marshaller marshaller = jaxbContext.createMarshaller();
9
10        StringWriter writer = new StringWriter();
11        marshaller.marshal(new Book(), writer);
12
13        log.debug("Book xml:\n {}", writer.toString());
14    }
15
16
17    @XmlAccessorType(XmlAccessType.FIELD)
18    @XmlRootElement(name = "book")
19    public static class Book {
20
21        @XmlElementRef(name = "price")
22        private Price price = new Price();
23
24
25    }
26
27    @XmlAccessorType(XmlAccessType.FIELD)
28    @XmlRootElement(name = "price")
29    public static class Price {
30        @XmlAttribute(name = "drawable")
31        private Boolean drawable = true; //you may want to set default value here
32
33        @XmlValue
34        private int priceValue = 1234;
35
36        public Boolean getDrawable() {
37            return drawable;
38        }
39
40        public void setDrawable(Boolean drawable) {
41            this.drawable = drawable;
42        }
43
44        public int getPriceValue() {
45            return priceValue;
46        }
47
48        public void setPriceValue(int priceValue) {
49            this.priceValue = priceValue;
50        }
51    }
52}
53
Full Screen
copy
1<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2<book>
3    <price drawable="true">1234</price>
4</book>
5
Full Screen
copy
1<?xml version="1.0" encoding="UTF-8"?>
2<schema xmlns="http://www.w3.org/2001/XMLSchema" 
3targetNamespace="http://www.example.org/Sport"
4xmlns:tns="http://www.example.org/Sport" 
5elementFormDefault="qualified"
6xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" 
7jaxb:version="2.0">
8
9<complexType name="sportType">
10    <simpleContent>
11        <extension base="string">
12            <attribute name="type" type="string" />
13            <attribute name="gender" type="string" />
14        </extension>
15    </simpleContent>
16</complexType>
17
18<element name="sports">
19    <complexType>
20        <sequence>
21            <element name="sport" minOccurs="0" maxOccurs="unbounded"
22                type="tns:sportType" />
23        </sequence>
24    </complexType>
25</element>
26
Full Screen
copy
1package org.example.sport;
2
3import javax.xml.bind.annotation.XmlAccessType;
4import javax.xml.bind.annotation.XmlAccessorType;
5import javax.xml.bind.annotation.XmlAttribute;
6import javax.xml.bind.annotation.XmlType;
7
8
9@XmlAccessorType(XmlAccessType.FIELD)
10@XmlType(name = "sportType")
11public class SportType {
12    @XmlValue
13    protected String value;
14    @XmlAttribute
15    protected String type;
16    @XmlAttribute
17    protected String gender;
18
19    public String getValue() {
20        return value;
21    }
22
23    public void setValue(String value) {
24        this.value = value;
25    }
26
27    public String getType() {
28    return type;
29    }
30
31
32    public void setType(String value) {
33        this.type = value;
34    }
35
36    public String getGender() {
37        return gender;
38    }
39
40    public void setGender(String value) {
41        this.gender = value;
42    }
43}
44
Full Screen
copy
1package org.example.sport;
2
3import javax.xml.bind.annotation.*;
4
5@XmlAccessorType(XmlAccessType.FIELD)
6@XmlRootElement
7public class Sport {
8
9    @XmlAttribute
10    protected String type;
11
12    @XmlAttribute
13    protected String gender;
14
15    @XmlValue;
16    protected String description;
17
18}
19
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)