我有一个id为属性的xml文件。
<?xml version="1.0" encoding="utf-8"?>
<animalguesser>
<query id = "1" >
<data> Welcome to Animal Guessing Game !!!!!!! </data>
<choices>
<choice jumptoid = "2" > continue </choice>
<choice jumptoid = "39" > exit </choice>
</choices>
</query>
<query id = "2" >
<data> Is this a mammal ? </data>
<choices>
<choice jumptoid = "3" > yes </choice>
<choice jumptoid = "11" > no </choice>
</choices>
我使用DOM解析了xml文件,我想做的是从用户那里获取输入,将它与选择的jumptoid匹配并返回结果并继续,是否有可以在dom和java中执行此操作?感谢
答案 0 :(得分:1)
试试这个:
String outputString="Your xml string";
Document document = parseXmlFile(outputString);
javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
System.out.println("Enter number ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
sc.close();
Element e = (Element) xpath.evaluate("//query[@id='"+i+ "']", document, XPathConstants.NODE);
使用示例XML进行测试并且工作正常。
有关语法规则,请参阅此站点
http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/