我有一些問題,當我使用if
語句for
環內的XML文檔中刪除一些節點,因爲我不明白爲什麼我的計數器成爲0把if
語句後:Java的XPath的「if」語句
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(new File("input3.xml"));
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expres = xpath.compile("//TNMS/TPaths/TPath[Topology/LayerSet/NonTerminatedLayers/Layer='RS64']");
NodeList PathsCount = (NodeList) expres.evaluate(document, XPathConstants.NODESET);
System.out.println("Inicia el Borrado:");
for (int i = 0; i < PathsCount.getLength(); i++)
{
System.out.println(i);
XPathExpression exprueba = xpath.compile("/TNMS/TPaths/TPath[1]/Topology/LayerSet/TerminatedLayers");
NodeList Count = (NodeList) exprueba.evaluate(document, XPathConstants.NODESET);
System.out.println("Hay " + Count.getLength());
int countvar = Count.getLength();
XPathExpression expression = xpath.compile("//TNMS/TPaths/TPath[Topology/LayerSet/NonTerminatedLayers/Layer='RS64']");
Node b13Node = (Node) expression.evaluate(document, XPathConstants.NODE);
b13Node.getParentNode().removeChild(b13Node);
}
我看到在輸出下一:
Inicia el Borrado:
0
Hay 0
1
Hay 1
2
Hay 1
3
Hay 0
<?xml version="1.0" encoding="UTF-8" standalone="no"?><TNMS>
<TPaths>
</TPaths>
</TNMS>BUILD SUCCESSFUL (total time: 0 seconds)
但是,當我同意if
聲明:
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(new File("input3.xml"));
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expres = xpath.compile("//TNMS/TPaths/TPath[Topology/LayerSet/NonTerminatedLayers/Layer='RS64']");
NodeList PathsCount = (NodeList) expres.evaluate(document, XPathConstants.NODESET);
System.out.println("Inicia el Borrado:");
for (int i = 0; i < PathsCount.getLength(); i++)
{
System.out.println(i);
XPathExpression exprueba = xpath.compile("/TNMS/TPaths/TPath[1]/Topology/LayerSet/TerminatedLayers");
NodeList Count = (NodeList) exprueba.evaluate(document, XPathConstants.NODESET);
System.out.println("Hay " + Count.getLength());
int countvar = Count.getLength();
if (countvar == 1) {
XPathExpression expression = xpath.compile("//TNMS/TPaths/TPath[Topology/LayerSet/NonTerminatedLayers/Layer='RS64']");
Node b13Node = (Node) expression.evaluate(document, XPathConstants.NODE);
b13Node.getParentNode().removeChild(b13Node);
}
}
輸出是下一個:
Inicia el Borrado:
0
Hay 0
1
Hay 0
2
Hay 0
3
Hay 0
和擦除失敗。
任何想法?
您的預期成果是什麼? 'if'語句中的代碼只會在'countvar'爲1時執行。但是什麼改變'countvar'?它有沒有改變? – alondono
請考慮發佈您的XML來源。如果問題出現在XPath表達式中,那麼沒有辦法在沒有看到XML源代碼的情況下對其進行測試。 – sideshowbarker
非常感謝您的回答,我沒有發佈XML,因爲它太分享了。但它可以用一些新的方法。 –