2016-03-20 12 views
0

したがって、XPathでXMLファイルを解析する必要があります。 すべてうまくいきますが、複数回存在するタグがある場合、私のコードはタグ内のすべての同じタグのすべてのサブタグを表示します。たとえば :私はXPathパーサーJava冗長性

<a> 
    <b></b> 
</a> 
<c></c> 
<a> 
    <b></b> 
</a> 

出力はされますがあります。

public void parseFileXPath() throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { 
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); 
    Document doc = documentBuilder.parse(file); 
    doc.getDocumentElement().normalize(); 

    XPathFactory factory = XPathFactory.newInstance(); 
    XPath xpath = factory.newXPath(); 

    String expression; 
    Node node; 
    NodeList nodeList; 

    expression="/*"; 
    node = (Node) xpath.evaluate(expression,doc, XPathConstants.NODE); 
    //System.out.println(node.getNodeName()); 

    expression="/frogans-fsdl/*"; 
    nodeList = (NodeList) xpath.evaluate(expression,doc, XPathConstants.NODESET); 


    NodeList nodeList1; 


    for (int i = 0; i < nodeList.getLength(); i++) { 
     String aTag = nodeList.item(i).getNodeName(); 

     System.out.println(aTag); 
     expression="/frogans-fsdl/"+aTag+"/*"; 
     nodeList1 = (NodeList) xpath.evaluate(expression,doc,XPathConstants.NODESET); 

     for (int j = 0; j < nodeList1.getLength(); j++) { 

      System.out.println("\t"+nodeList1.item(j).getNodeName()); 
      //TODO 
      //Display what's inside each tag 
     } 

     expression=""; 
    } 



} 

すべてのヘルプしてください:

a 
b 
b 
c 
a 
b 
b 

私のコードは、このですか?

答えて

1

次内部ループコードは出力が欲しいものを助けるかもしれない:

NodeList nodeList1; 

    for (int i = 0; i < nodeList.getLength(); i++) { 
     System.out.println(nodeList.item(i).getNodeName()); 
     expression="*"; 
     nodeList1 = (NodeList) xpath.evaluate(expression,nodeList.item(i),XPathConstants.NODESET); 
     for (int j = 0; j < nodeList1.getLength(); j++) { 
      System.out.println("\t"+nodeList1.item(j).getNodeName()); 
     } 
    } 

基本的には、その後のXPath評価で2番目の引数としてnodeList.item(i)を渡す必要があります。

+0

ありがとうございました! –

0

最初のxathはfrogans-fsdlのすべての子を見つけます。おそらくa,c,a /frogans-fsdl/a/*"で、/ frogans-fsdl/a /、/ frogans-fsdl/c /および/ frogans-fsdl/a/againのすべての子どものwholドキュメントを探しています。

2番目のxpahtを*に変更し、2番目の評価呼び出しのコンテキストノードとしてnodeList.item(i)を使用する必要があります。

+0

うん、私はマヘスの反応からそれを得た、私はとても愚かだった私は私がファイル全体を再解析しているとは思わなかった。 –