简体   繁体   English

在Java中创建Xpath以基于另一个属性值选择一个属性值

[英]Creating an Xpath in java to select an attribute value based on another attribute value

I know this is related to many questions out there, but I could not find an example that used an xml layout like mine. 我知道这与那里的许多问题有关,但是我找不到使用像我的xml布局的示例。

<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>

I am looping through a properties file that specifies which products we're interested within the xml and am having a hard time creating the right expression. 我正在遍历一个属性文件,该文件指定了我们在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);
     }
}

So I want to be able to select the count, and in the future, occured_at_time, with this expression "product[@name=" + Products[j] + "]attribute::count". 因此,我希望能够使用此表达式“ product [@ name =“ + Products [j] +”] attribute :: count”来选择计数,并在将来发生出现时间。 Really I just need to know if this is possible given the circumstances, or I need to come at this a different way. 真的,我只需要知道在特定情况下是否可行,或者我需要以其他方式来解决这个问题。

You want xpath.compile("product[@name='" + Products[j] + "']/attribute::count"); 您需要xpath.compile("product[@name='" + Products[j] + "']/attribute::count"); or xpath.compile("product[@name='" + Products[j] + "']/@count"); xpath.compile("product[@name='" + Products[j] + "']/@count"); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM