java - 编辑 XML 文件无法正常工作

标签 java xml

我正在使用此脚本来编辑 XML 文件。 TestNG 使用此 XML 文件来运行测试。它包含有关我想要运行的测试的信息。运行测试后,我想更新 XML 文件,例如测试结果的位置。

我写这个脚本是为了做我想做的事;

public void editXMLFile(String nameOfTest, String resultLoc){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder;
        Document doc = null;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse("testng.xml");

            NodeList tests = doc.getElementsByTagName("test");
            Element test = null;
            for (int i = 0; i < tests.getLength(); i++) {
                test = (Element) tests.item(i);
                String testNames = test.getAttribute("name");
                if (testNames.equals(nameOfTest)) {
                    //System.out.println("Found element!");
                    NodeList params = test.getElementsByTagName("parameter");
                    Element runType = null, baselineLocation = null;
                    for (int i1 = 0; i1 < params.getLength(); i1++) {
                        runType = (Element) params.item(i1);
                        String paramNames = runType.getAttribute("name");
                        if (paramNames.equalsIgnoreCase("runType")) {
                            //System.out.println("Found the runType");
                            if (runType.getAttribute("value").equalsIgnoreCase(
                                    "baseline")) {
                                for (int j = 0; j < params.getLength(); j++) {
                                    baselineLocation = (Element) params.item(j);
                                    if (baselineLocation.getAttribute("name")
                                            .equalsIgnoreCase("baselineLocation")) {
                                        //System.out.println("Found baselineLocation!");
                                        runType.setAttribute("value", "actual");
                                        baselineLocation.setAttribute("value", resultLoc);
                                        System.out.println("resultLoc = " + resultLoc);
                                        System.out.println("Test name = " + _testName);
                                        // Prepare the DOM document for writing
                                        Source source = new DOMSource(doc);

                                        // Prepare the output file
                                        File file = new File("C:/Users/sfd/Desktop/testng.xml");
                                        StreamResult sr = new StreamResult(file);
                                        Result result = sr;


                                        // Write the DOM document to the file
                                        Transformer xformer = TransformerFactory
                                                .newInstance().newTransformer();
                                        xformer.transform(source, result);

                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

这是 XML 文件;

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Test Suite Name" parallel="none">
<listeners>
    <listener class-name="testng.MyListener"></listener>
</listeners>
<test name="Test NOT on localhost">
    <parameter name="Browser" value="chrome"/> <!-- chrome or firefox or IE or Android Native-->
    <parameter name="url" value='' /> <!-- URL of the webpage you want to test -->
    <parameter name="CSV" value="testdata.csv"/> <!-- Location of the CSV file that you want to run tests with -->
    <parameter name="resultLocation" value="C:\Users\sfd\Desktop"/> <!-- TestNG will create two folder in this location, screenshots and test-output-datestamp -->
    <parameter name="baselineLocation" value=""/> <!-- Location of the baseline location -->
    <parameter name="runType" value="baseline" /> <!--  actual or baseline . baseline = first run. actual is second run, to do a compare for example -->
    <classes>
      <class name="testng.runTest"></class>
    </classes>
  </test> <!-- Test CAN YOU SEE THIS?-->
  <test name="Test localhost">
    <parameter name="Browser" value="chrome"/> <!-- chrome or firefox or IE or Android Native-->
    <parameter name="url" value='' />
    <parameter name="CSV" value="testdata.csv"/>
    <parameter name="resultLocation" value="C:\Users\sfd\Desktop\testmap"/> <!-- TestNG will create two folder in this location, screenshots and test-output-datestamp -->
    <parameter name="baselineLocation" value=""/> <!-- Location of the baseline run. leave value empty. This will be filled in by TestNG itself. -->
    <parameter name="runType" value="baseline" /> <!--  actual or baseline . baseline = first run. actual is second run, to do a compare for example -->
    <classes>
      <class name="testng.runTest"></class>
    </classes>
  </test>
</suite> <!-- Suite end of suite -->

我面临的问题如下;当我的 xml 文件中只有 1 个测试时,它工作正常。但是,当我在 XML 文件中有超过 1 个测试时,只有最后一个测试会被更新。两个测试的基线位置都应该更新,而只有最后一个测试会更新。我认为这个方法的逻辑有缺陷,但我不确定具体是什么。

最佳答案

如果多次调用 editXMLFile() 来更新多个测试名称,则会出现问题。您正在该方法中编写更新的 XML 文件。由一个测试名称匹配创建的 XML 将被后续测试名称匹配条件覆盖。

您需要推迟写入 XML 文件,直到使用所有测试名称更新了 doc 对象。

一种可能的重构解决方案

private Document createXMLDocument() // move the XML document for test.xml logic into this method

public Document editXMLFile(Document doc, String nameOfTest, String resultLoc) // assuming you don't have any constraint on method signature. Return back updated Document object.

private Document getUpdatedXMLDocument(Document doc) // move your filtering condition logic into this. Call this from editXMLFile()

private void writeUpdatedXMLFile(Document doc) // move out the logic of writing the new XML file here. Call this after final call to editXMLFile()

希望这能给出一个公平的想法。

关于java - 编辑 XML 文件无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27988556/

相关文章:

在 DB2 中执行更新查询的 Java 程序显示 SqlSyntaxErrorException

java - 支持 Servlet 3.0 的最低 Wildfly 版本

xml - 我需要一个模式规则,仅当另一个属性首先存在时才强制执行该属性的存在。

Android 进度条在将其样式从 progressBarStyleHorizo​​ntal 更改为 progressBarStyleInverse 时始终不确定

xml - 在Scala中评估Xpath

java - 是否有 Java 库来验证 XML 片段是较大 XML 文件的子集?

Java ArrayList 给我一个不安全操作警告

java - Android Java 文件创建 java.io.FileNotFoundException(文件名太长)

java - MockwebServer 不模拟 http 调用

java - 如何在java中转换具有 "ref ids"和 "ids"的XML文件