如何使用java从xml中获取特定的整个标记值

pgccezyw  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(317)

我尝试了下面的代码从xml文件中获取特定的整个标记值
xml结构:

<?xml version="1.0" encoding="UTF-8"?>
    <test-result>
    <test-method status="PASS" name="beforeTestSetup" is-config="true" duration-ms="705" started-at="2018-08-16T21:39:59Z" finished-at="2018-08-16T21:39:59Z">
    <params>
    <param index="0">
    <value> <![CDATA[org.testng.TestRunner@31c2affc]]> </value>
    </param>
    </params>   
    </test-method>
    <test-method status="FAIL" name="beforeTestSetup" is-config="true" duration-ms="805" started-at="2018-08-16T21:39:59Z" finished-at="2018-08-16T21:39:59Z">
    <params>
    <param index="0">
    <value> <![CDATA[org.testng.TestRunner@31c2affc]]> </value>
    </param>
    </params>   
    </test-method>
    <test-method status="PASS" name="TEST" is-config="true" duration-ms="905" started-at="2018-08-16T21:39:59Z" finished-at="2018-08-16T21:39:59Z">
    <params>
    <param index="0">
    <value> <![CDATA[org.testng.TestRunner@31c2affc]]> </value>
    </param>
    </params>   
    </test-method>      
    </test-result>

代码:

docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   is = new InputSource();
   is.setCharacterStream(new StringReader(content));
   doc = docBuilder.parse(is);
   NodeList rootElement = doc.getElementsByTagName("test-method");
   for (int i = 0; i < rootElement.getLength(); i++) 
    {
      Element element=(Element)rootElement.item(i);
       if(element.getAttribute("status").equals("PASS"))
       {
          System.out.println(element.getTextContent());
       }
    }

上述代码未按预期工作。
我只想得到test method status=“pass”并跳过这个负载中剩下的内容。预期产量如下:
预期输出(它应该获得整个标记及其值):

<test-method status="PASS" name="beforeTestSetup" is-config="true" duration-ms="705" started-at="2018-08-16T21:39:59Z" finished-at="2018-08-16T21:39:59Z">
     <params>
     <param index="0">
     <value> <![CDATA[org.testng.TestRunner@31c2affc]]> </value>
     </param>
     </params>  
     </test-method>
     <test-method status="PASS" name="TEST" is-config="true" duration-ms="905" started-at="2018-08-16T21:39:59Z" finished-at="2018-08-16T21:39:59Z">
     <params>
     <param index="0">
     <value> <![CDATA[org.testng.TestRunner@31c2affc]]> </value>
     </param>
     </params>  
     </test-method>

上述结果应跳过“失败”状态的结果。
有人帮我解决这个问题吗

qojgxg4l

qojgxg4l1#

您好,请通过替换

System.out.println(element.getTextContent());

System.out.println(description(element, ""));

public  String description(Node n, String tab){
        String str = new String();
        if(n instanceof Element){
            Element element = (Element)n;
            str += "<" + n.getNodeName();
            if(n.getAttributes() != null && n.getAttributes().getLength() > 0){
                NamedNodeMap att = n.getAttributes();
                int nbAtt = att.getLength();
                for(int j = 0; j < nbAtt; j++){
                    Node noeud = att.item(j);
                    str += " " + noeud.getNodeName() + "=\"" + noeud.getNodeValue() + "\" ";
                }
            }
            str += ">";
            if(n.getTextContent()!= null ){
                str += "<![CDATA[" + n.getTextContent().replace("\n", "").trim()+ "]]";
            }
            if(n.getChildNodes().getLength() == 1)
                str += n.getTextContent();
            int nbChild = n.getChildNodes().getLength();
            NodeList list = n.getChildNodes();
            String tab2 = tab + "\t";
            for(int i = 0; i < nbChild; i++){
                Node n2 = list.item(i);
                if (n2 instanceof Element){

                    str += "\n " + tab2 + description(n2, tab2);
                }
            }
            if(n.getChildNodes().getLength() < 2)
                str += "</" + n.getNodeName() + ">";
            else
                str += "\n" + tab +"</" + n.getNodeName() + ">";
        }
        return str;
    }
c3frrgcw

c3frrgcw2#

对于这种情况,请考虑改用xslt。带有标识转换的xslt样式表以及对选定元素的特殊处理将非常有效。

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="test-method[@status = 'FAIL']"/>
</xsl:stylesheet>

第一个模板匹配所有类型的节点,创建节点的副本,然后递归地将模板应用于子节点。
第二个模板将匹配 test-method 具有名为 status 有价值的 FAIL . 由于此模板不执行任何操作,因此 test-method 元素和所有子节点将被过滤掉。
下面是一个完整的示例:

static String XSL =
        "<xsl:stylesheet version=\"1.0\"\n" +
        "    xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n" +
        "    <xsl:template match=\"@*|node()\">\n" +
        "        <xsl:copy>\n" +
        "            <xsl:apply-templates select=\"@*|node()\" />\n" +
        "        </xsl:copy>\n" +
        "    </xsl:template>\n" +
        "\n" +
        "    <xsl:template match=\"test-method[@status = 'FAIL']\"/>\n" +
        "</xsl:stylesheet>";

static String XML =
        "<test-result>\n" +
        "    <test-method status=\"PASS\" name=\"beforeTestSetup\"\n" +
        "        is-config=\"true\" duration-ms=\"705\"\n" +
        "        started-at=\"2018-08-16T21:39:59Z\"\n" +
        "        finished-at=\"2018-08-16T21:39:59Z\">\n" +
        "        <params>\n" +
        "            <param index=\"0\">\n" +
        "                <value> <![CDATA[org.testng.TestRunner@31c2affc]]>\n" +
        "                </value>\n" +
        "            </param>\n" +
        "        </params>\n" +
        "    </test-method>\n" +
        "    <test-method status=\"FAIL\" name=\"beforeTestSetup\"\n" +
        "        is-config=\"true\" duration-ms=\"805\"\n" +
        "        started-at=\"2018-08-16T21:39:59Z\"\n" +
        "        finished-at=\"2018-08-16T21:39:59Z\">\n" +
        "        <params>\n" +
        "            <param index=\"0\">\n" +
        "                <value> <![CDATA[org.testng.TestRunner@31c2affc]]>\n" +
        "                </value>\n" +
        "            </param>\n" +
        "        </params>\n" +
        "    </test-method>\n" +
        "    <test-method status=\"PASS\" name=\"TEST\" is-config=\"true\"\n" +
        "        duration-ms=\"905\" started-at=\"2018-08-16T21:39:59Z\"\n" +
        "        finished-at=\"2018-08-16T21:39:59Z\">\n" +
        "        <params>\n" +
        "            <param index=\"0\">\n" +
        "                <value> <![CDATA[org.testng.TestRunner@31c2affc]]>\n" +
        "                </value>\n" +
        "            </param>\n" +
        "        </params>\n" +
        "    </test-method>\n" +
        "</test-result>";

public static void main(String[] args) throws Exception {
    Transformer t = TransformerFactory.
            newInstance()
            .newTransformer(new StreamSource(new StringReader(XSL)));

    t.transform(new StreamSource(new StringReader(XML)), new StreamResult(System.out));

}

相关问题