I would like to have Java generate a ‘0’ in case an XPath expression evaluates to ‘false’.
I have this Java code:
//Read the input XML document
private SAXBuilder parser = new SAXBuilder();
private Document characters;
private XPath pProbs;
private List<Attribute> probs;
private Double[] dprobs;
private String pathToSourceXml;
private String content1, content2, content3, content4, content5;
characters = parser.build(pathToSourceXml);
pProbs = XPath.newInstance("/n-grams-sorted/n-gram[contains(.,"+content1+") or contains(.,"+content2+") or contains(.,"+content3+") or contains(.,"+content4+") or contains(.,"+content5+")]/@probability");
probs = (List<Attribute>) pProbs.selectNodes(characters);
...
//Return all the values of the @probability attibrutes
public Double[] getProbs(String pathToSourceXml) {
this.pathToSourceXml = pathToSourceXml;
List<Double> theDoubles = new ArrayList();
dprobs = new Double[5];
for (int i=0; i<probs.size(); i++) {
theDoubles.add(Double.parseDouble(probs.get(i).getValue()));
dprobs[i] = theDoubles.get(i);
}
return dprobs;
}
The problem here is that this code:
pProbs = XPath.newInstance("/n-grams-sorted/n-gram[contains(.,"+content1+") or contains(.,"+content2+") or contains(.,"+content3+") or contains(.,"+content4+") or contains(.,"+content5+")]/@probability");
only returns 4 elements because ‘content1’ returns ‘false’. There are no n-gram nodes whose content contains the string ‘$ $ $’. However, the rest of the content nodes evaluates to ‘true’.
If one of these contains() expressions evaluates to ‘false’, I must draw a ‘0’ in my Xaml code. A ‘0’ must appear on the screen, such as:
'# # #' = 0.0015
'? ? ?' = 0.0047
'k i d' = 0.0012
'$ $ $' = 0
I can’t fetch this ‘0’. I don’t know how to say: “return a zero in case that there are no nodes that contain ‘$ $ $’ as content.
Any ideas on how to do this?
Thank you.
Here is the answer:
(This code is not working for what I want to accomplish outside of this question, but it works for this question because I have a way of returning a ‘0’ in java, when the XPath expression yields zero-length).
The solution is this part really: