Chad
Chad

Reputation: 51

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.

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

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". Really I just need to know if this is possible given the circumstances, or I need to come at this a different way.

Upvotes: 0

Views: 98

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167726

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

Upvotes: 1

Related Questions