如何动态地从java创建xml文件中的节点中的节点

时间:2016-04-29 06:07:05

标签: java xml dynamic xml-parsing testng

这是我想用java代码动态创建的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="4" name="cool" verbose="5" parallel="tests">

 <test name="test_case6" parallel="tests">
    <parameter name="testsuite" value="Fleet"/>
    <parameter name="className" value="Fleet"/>
    <parameter name="methodName" value="TC_02"/>
    <parameter name="runtype" value="mobile"/>
    <parameter name="browser" value="NA"/>
    <parameter name="width_height" value="NA"/>
    <parameter name="deviceName" value="LGG3"/>
    <parameter name="deviceVersion" value="20"/>
    <parameter name="reportFolderName" value="Report6"/>
    <classes>
      <class name="com.igate.tests.GalenParallelMain">
      </class>
    </classes>
  </test>
</suite>

此处name属性值是硬编码的,但value属性值将动态生成。 我试着搜索这个,但所有的例子都很简单。

1 个答案:

答案 0 :(得分:0)

据我了解,您想通过TestNG API创建它,不是吗?

    XmlClass xmlClass = new XmlClass();
    xmlClass.setName("com.igate.tests.GalenParallelMain");
    //        xmlClass.setClass(GalenParallelMain.class);

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("runtype", "mobile");
    parameters.put("browser", "na");
    // ...

    XmlSuite xmlSuite = new XmlSuite();
    xmlSuite.setName("cool");
    xmlSuite.setThreadCount(4);
    xmlSuite.setVerbose(5);
    xmlSuite.setParallel("tests");

    XmlTest xmlTest = new XmlTest(xmlSuite);
    xmlTest.setName("test_case6");
    xmlTest.setParallel("tests");
    xmlTest.setParameters(parameters);
    xmlTest.setClasses(Arrays.asList(xmlClass));

    // the XML you requested
    System.out.println(xmlSuite.toXml());

    TestNG testNG = new TestNG();
    testNG.setXmlSuites(Arrays.asList(xmlSuite));
    testNG.run();