2013-12-13 35 views
0

我知道这与许多问题有关,但我找不到使用xml布局的示例,例如我的。在java中创建Xpath以根据另一个属性值选择属性值

<product name="ANALYTICS" count="24" occurred_at_time="1386648300000"> 
    <user_type name="Unknown" count="24" occurred_at_time="1386648300000"> 
     <session_source name="Web" count="24" occurred_at_time="1386648300000"/> 
    </user_type> 
</product> 
<product name="CARSWELL" count="492" occurred_at_time="1386651900000"> 
    <user_type name="External" count="492" occurred_at_time="1386651900000"> 
     <session_source name="Web" count="492" occurred_at_time="1386651900000"/> 
    </user_type> 
    <user_type name="Internal" count="19" occurred_at_time="1386622200000"> 
     <session_source name="UNKNOWN" count="12" occurred_at_time="1386624300000" /> 
     <session_source name="Web" count="10" occurred_at_time="1386604200000" /> 
    </user_type> 
</product> 

我正在循环一个属性文件,该文件指定我们在xml中感兴趣的产品,并且很难创建正确的表达式。

for (int j = 0; j < Products.length; j++) { 
    XPathFactory xPathfactory = XPathFactory.newInstance(); 
    XPath xpath = xPathfactory.newXPath(); 

    try { 
      XPathExpression expr = xpath.compile("product[@name=" + Products[j] + "]attribute::count"); 
      CompareNextWeb = expr.evaluate(doc); 
      System.out.println(CompareNextWeb); 

    } catch (XPathExpressionException ex) { 
      Logger.getLogger(NextReport.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

所以我希望能够选择计数,而在未来,occured_at_time,这种表达“产品[@名称=” +产品[J] +“]属性::计数”。真的,我只是需要知道在情况下这是否可能,或者我需要以不同的方式来实现。

回答

1

你想要xpath.compile("product[@name='" + Products[j] + "']/attribute::count");xpath.compile("product[@name='" + Products[j] + "']/@count");

+0

完美,谢谢! – Chad