2016-01-13 71 views
-4

我的.xml文档以获得以xml一种元素的标签的数量包含数据是这样的:如何使用XML或Java代码

<Test-Set> 
<Test-Case Name="Verify using Interface user in WebService we are able to do database transactions" /> 
<Test-Case Name="Verify using Interface user in JMS we are able to post a message to queue and get message from queue" /> 
<Test-Case Name="Verify using Interface user we are able to login BPD"/> 
</Test-Set> 

我的预期的输出是:3

+1

请显示您写的代码,您期望得到的结果,并描述您遇到的问题。否则,我们无法帮助你。请参阅[这里](http://stackoverflow.com/help/mcve)以获取关于创建最小,完整和可验证示例的更多信息,这将有助于我们回答您的问题。 – Sam

+0

你尝试过什么吗? –

+0

看看http://stackoverflow.com/help/how-to-ask,否则你会得到downvotes – SSH

回答

0

未测试:

public class Demo { 

    public static void main(String[] args) throws Exception { 
     String xml = "<Test-Set> " + 
        "<Test-Case Name=\"Verify using Interface user in WebService we are able to do database transactions\" />" + 
        "<Test-Case Name=\"Verify using Interface user in JMS we are able to post a message to queue and get message from queue\" />" + 
        "<Test-Case Name=\"Verify using Interface user we are able to login BPD\"/>" + 
        "</Test-Set>"; 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 

     DocumentBuilder builder = factory.newDocumentBuilder(); 

     Document document = builder.parse(new ByteArrayInputStream(xml.getBytes())); 
     String xpath = "count(Test-Set/TestCase)"; 
     XPath xPath = XPathFactory.newInstance().newXPath(); 
     Double s = (Double) xPath.evaluate(xpath, document, XPathConstants.NUMBER); 
    } 

}