2017-02-22 7 views
0

属性としてidを持つxmlファイルがあります。Javaで要素の属性値を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でこれを行うことができます方法はありますか?おかげ

答えて

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/

+0

いくつかの構文規則のためにも、このサイトを参照してください。その1を続行し、2の選択肢jumptoidに一致する必要があり、クエリID 2のデータを表示する必要があります。 – Kaijju

+0

ユーザーからの入力を取得し、指定されたIDに基づいてテキストを取得するように変更されました。内部でスキャナとハッシュマップを使用してください。 – HaroonIsmailbasha

関連する問題