如何在现有XML文件中附加一个XML标签

时间:2018-12-06 18:49:56

标签: java xml dom

我只想将以下XML标记附加到现有XML中。但是当我尝试执行该操作时,它会抛出以下错误消息。

  

[致命错误]:9:16:根目录后的文档中的标记   元素必须格式正确。线程“主”中的异常   org.xml.sax.SAXParseException; lineNumber:9; columnNumber:16;的   根元素后面的文档中的标记必须格式正确。

以下试图添加到现有XML中的片段:

<test-method duration-ms="4"  finished-at="2018-08-16T21:46:55Z"  is-config="true"  test-instance-name="DummyTestcase" >
    <reporter-output>
        <line>
        </line>
    </reporter-output>
</test-method>

现有XML文件:

   <?xml version="1.0" encoding="UTF-8"?>
    <testng-results skipped="0" failed="0" total="10" passed="10">
        <test-method status="FAIL" is-config="true" duration-ms="4"
            started-at="2018-08-16T21:43:38Z" finished-at="2018-08-16T21:43:38Z">
            <params>
                <param index="0">
                    <value>               
          <![CDATA[org.testng.TestRunner@31c2affc]]>
                    </value>
                </param>
            </params>
            <reporter-output>
            </reporter-output>
        </test-method> <!-- setParameter -->


        <test-method status="FAIL" is-config="true" duration-ms="5"
            started-at="2018-08-16T21:44:55Z" finished-at="2018-08-16T21:44:55Z">
            <reporter-output>
                <line>             
         <![CDATA[runSettlement Value Set :false]]>
                </line>
            </reporter-output>
        </test-method> <!-- setSettlementFlag -->

    </testng-results>

代码:

        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        is = new InputSource();
        is.setCharacterStream(new StringReader(content));
        doc = docBuilder.parse(is);
        NodeList rootElement = doc.getElementsByTagName("test-method");
        Element element=(Element)rootElement.item(0);

        StringBuilder sb=new StringBuilder();

        for(String str:dataObj)
        {
            sb.append(str);
        }

        String getContent=sb.toString();

        System.out.println(getContent);

        docBuilder1 = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        is1 = new InputSource();
        is1.setCharacterStream(new StringReader(getContent));
        doc1 = docBuilder1.parse(is1);

        Node copiedNode = (Node) doc1.importNode(element, true);

        doc1.getDocumentElement().appendChild(copiedNode);

预期输出:

    <?xml version="1.0" encoding="UTF-8"?>
    <testng-results skipped="0" failed="0" total="10" passed="10">
        <test-method status="FAIL" is-config="true" duration-ms="4"
            started-at="2018-08-16T21:43:38Z" finished-at="2018-08-16T21:43:38Z">
            <params>
                <param index="0">
                    <value>              
          <![CDATA[org.testng.TestRunner@31c2affc]]>
                    </value>
                </param>
            </params>
            <reporter-output>
            </reporter-output>
        </test-method> <!-- setParameter -->
        <test-method status="FAIL" is-config="true" duration-ms="5"
            started-at="2018-08-16T21:44:55Z" finished-at="2018-08-16T21:44:55Z">
            <reporter-output>
                <line>                   
        <![CDATA[runSettlement Value Set :false]]>
                </line>
            </reporter-output>
        </test-method> <!-- setSettlementFlag -->

<!--The below lines are appended -->
         </test-method><test-method duration-ms="4"  finished-at="2018-08-16T21:46:55Z"  is-config="true"  test-instance-name="DummyTestcase" >
            <reporter-output>
                <line>
                </line>
            </reporter-output>
    </test-method>

</testng-results>

上面的XML标记应最后添加到现有XML文件的最后,如上所示。

任何人都可以分享一些想法来实现这一目标吗?

2 个答案:

答案 0 :(得分:0)

在XML中可见

  1. testing-results是rootElement。
  2. 此外,测试方法是子元素。

因此,如果要添加 test-method 作为子元素,请将其附加到 testing-reults 元素,而不是将其附加到 test-method 。另外,我认为您将test-method用作附加此代码的根元素

NodeList rootElement = doc.getElementsByTagName("test-method");

答案 1 :(得分:0)

这是一个例子:

static String EXISTING =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<testng-results skipped=\"0\" failed=\"0\" total=\"10\"\n" +
        "    passed=\"10\">\n" +
        "    <test-method status=\"FAIL\" is-config=\"true\"\n" +
        "        duration-ms=\"4\" started-at=\"2018-08-16T21:43:38Z\"\n" +
        "        finished-at=\"2018-08-16T21:43:38Z\">\n" +
        "        <params>\n" +
        "            <param index=\"0\">\n" +
        "                <value>\n" +
        "          <![CDATA[org.testng.TestRunner@31c2affc]]>\n" +
        "                </value>\n" +
        "            </param>\n" +
        "        </params>\n" +
        "        <reporter-output>\n" +
        "        </reporter-output>\n" +
        "    </test-method> <!-- setParameter -->\n" +
        "\n" +
        "    <test-method status=\"FAIL\" is-config=\"true\"\n" +
        "        duration-ms=\"5\" started-at=\"2018-08-16T21:44:55Z\"\n" +
        "        finished-at=\"2018-08-16T21:44:55Z\">\n" +
        "        <reporter-output>\n" +
        "            <line>\n" +
        "         <![CDATA[runSettlement Value Set :false]]>\n" +
        "            </line>\n" +
        "        </reporter-output>\n" +
        "    </test-method> <!-- setSettlementFlag -->\n" +
        "\n" +
        "</testng-results>";

static String APPEND =
        "<test-method duration-ms=\"4\"  finished-at=\"2018-08-16T21:46:55Z\"  is-config=\"true\"  test-instance-name=\"DummyTestcase\" >\n" +
        "    <reporter-output>\n" +
        "        <line>\n" +
        "        </line>\n" +
        "    </reporter-output>\n" +
        "</test-method>";

public static void main(String[] args) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    Document existingDoc = builder.parse(
            new ByteArrayInputStream(EXISTING.getBytes(StandardCharsets.UTF_8)));
    Document appendDoc = builder.parse(
            new ByteArrayInputStream(APPEND.getBytes(StandardCharsets.UTF_8)));

    Node root = existingDoc.getDocumentElement();

    root.appendChild(existingDoc.importNode(appendDoc.getDocumentElement(), true));
    root.appendChild(existingDoc.createTextNode("\n"));
    print(existingDoc);
}

static void print(Document doc) throws Exception {
    TransformerFactory.newInstance()
        .newTransformer()
        .transform(new DOMSource(doc), new StreamResult(System.out));
}