1package org.testng.xml.dom;
2
3import org.testng.xml.ISuiteParser;
4import org.testng.xml.XMLParser;
5import org.testng.xml.XmlSuite;
6import org.w3c.dom.Document;
7import org.xml.sax.SAXException;
8
9import javax.xml.parsers.DocumentBuilder;
10import javax.xml.parsers.DocumentBuilderFactory;
11import javax.xml.parsers.ParserConfigurationException;
12import javax.xml.xpath.XPathExpressionException;
13
14import java.io.IOException;
15import java.io.InputStream;
16
17public class DomXmlParser extends XMLParser<XmlSuite> implements ISuiteParser {
18  @Override
19  public XmlSuite parse(String currentFile, InputStream inputStream, boolean loadClasses) {
20    XmlSuite result = null;
21    try {
22      result = parse2(currentFile, inputStream, loadClasses);
23    } catch (Exception e) {
24      e.printStackTrace();
25    }
26
27    return result;
28  }
29
30  @Override
31  public boolean accept(String fileName) {
32    return fileName.endsWith(".xml");
33  }
34
35  public XmlSuite parse2(String currentFile, InputStream inputStream,
36      boolean loadClasses) throws ParserConfigurationException, SAXException,
37      IOException, XPathExpressionException {
38    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
39    factory.setNamespaceAware(true); // never forget this!
40    DocumentBuilder builder = factory.newDocumentBuilder();
41    Document doc = builder.parse(inputStream);
42
43    DomUtil xpu = new DomUtil(doc);
44    XmlSuite result = new XmlSuite();
45    xpu.populate(result);
46//    XPathFactory xpathFactory = XPathFactory.newInstance();
47//    XPath xpath = xpathFactory.newXPath();
48//
49//    {
50//      XPathExpression expr = xpath.compile("//suite");
51//      Object result = expr.evaluate(doc, XPathConstants.NODESET);
52//      NodeList nodes = (NodeList) result;
53//      for (int i = 0; i < nodes.getLength(); i++) {
54//        Node node = nodes.item(i);
55//        for (int j = 0; j < node.getAttributes().getLength(); j++) {
56//          System.out.println(node.getAttributes().item(j));
57//        }
58//      }
59//    }
60
61//    {
62//      XPathExpression expr = xpath.compile("//suite/@name");
63//      Object result = expr.evaluate(doc, XPathConstants.STRING);
64//      System.out.println("NAME:" + result);
65//    }
66    System.out.println(result.toXml());
67    return result;
68  }
69}
70