在给定的 XML 文件中,我尝试使用 Java 中的 XPath
搜索字符串是否存在。然而,即使字符串在那里,我的输出总是显示为否。希望这里有人能指出我可能做错了什么?
XML 文件:
<article>
<body>
<section>
<h1>intro1</h1>
<region>introd1</region>
<region>introd2</region>
</section>
<section>
<h1 class="pass">1 task objectives</h1>
<region>object1</region>
<region>object2</region>
</section>
<section>
<h1 class="pass">1 task objectives</h1>
<region>object1</region>
<region>This is the Perfect Word I am looking for</region>
</section>
</body>
</article>
在 Java 中,我正在尝试检查单词 “perfect”
是否存在,如下所示:
expr = xpath.compile("//article//body//section//region[contains(.,'perfect')]");
object result = expr.evaluate(doc,XPathConstants.NODESET);
NodeList nodes = (NodeList)result;
if (nodes.getLength() > 0) {
System.out.println("Found");
// do other stuff here
} else {
System.out.println("Not found");
}
当我运行它时,输出总是"Not Found"
。知道我做错了什么吗?
最佳答案
我测试过这个...
expr =xpath.compile("/article/body/section/region[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'perfect')]");
反对
<article>
<body>
<section>
<h1>intro1</h1>
<region>perfect</region>
<region>Perfect</region>
</section>
<section>
<h1 class="pass">1 task objectives</h1>
<region>pErFeCt</region>
<region>Not Perfect</region>
</section>
<section>
<h1 class="pass">1 task objectives</h1>
<region>object1</region>
<region>This is the Perfect Word I am looking for</region>
</section>
</body>
</article>
使用...
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class TestXML05 {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(new File("Sample.xml"));
XPathFactory xFactory = XPathFactory.newInstance();
XPath xPath = xFactory.newXPath();
XPathExpression exp = xPath.compile("/article/body/section/region[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'perfect')]");
NodeList nl = (NodeList)exp.evaluate(doc.getFirstChild(), XPathConstants.NODESET);
for (int index = 0; index < nl.getLength(); index++) {
Node node = nl.item(index);
System.out.println(node.getTextContent());
}
} catch (Exception ex) {
Logger.getLogger(TestXML05.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
哪个输出...
perfect
Perfect
pErFeCt
Not Perfect
This is the Perfect Word I am looking for
关于java - 在 XML 文件中搜索元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139759/