2016-04-27 5 views
1

私はXPathを検出しましたが、XMLファイルを解析するためにXPathを使用しようとしています。私はそれについていくつかのコースを読んだが、問題が残っている。私は、ファイルからのNodeListを取得しようとすると、私は(私の場合は7)出力が正しいインコヒーレントXPath出力

document.getElementsByTagName("crtx:env").getLength() 

をしようとすると、のgetLength()メソッドは常に、しかし0 を返します。 私のノーストリストは私の文書に従って作成されているので、出力は似ているはずですね。ここで

は、私のコードの一部です:

IFile     f    = (IFile) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorInput().getAdapter(IFile.class); 
    String     fileURL   = f.getLocation().toOSString(); 
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder   builder   = null; 

    try { 
     builder = builderFactory.newDocumentBuilder(); 
    } catch (ParserConfigurationException e) { 
     e.printStackTrace(); 
    } 

    Document document = null; 

    if (builder != null){ 
     try{ 
      document = builder.parse(fileURL); 
      System.out.println("DOCUMENT URI : " + document.getDocumentURI()); 
     } catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } else { 
     System.out.println("builder null"); 
    } 


    XPath xPath = XPathFactory.newInstance().newXPath(); 

    NodeList nodeList = null; 

    try { 
     nodeList = (NodeList) xPath.compile("crtx:env").evaluate(document, XPathConstants.NODESET); 
    } catch (XPathExpressionException e) { 
     e.printStackTrace(); 
    } 

    System.out.println("NODELIST SIZE : " + nodeList.getLength()); 
    System.out.println(document.getElementsByTagName("crtx:env").getLength()); 

} 

最初のSystem.out.println()コヒーレント出力(良いURI)を返しますが、2つの最後の行は、別の番号を返します。

ご協力いただければ幸いです。 読んでいただきありがとうございます。

答えて

1

のXPathは、名前空間とXMLのために定義されたので、ためhttps://xml.apache.org/xalan-j/xpath_apis.html#namespacecontextを参照してくださいあなたが名前空間URIに使用される接頭語(es)をバインドするhttps://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/XPath.html#setNamespaceContext%28javax.xml.namespace.NamespaceContext%29を使用する必要がある名前空間接頭辞とパスを使用するように次に

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
builderFactory.setNamespaceAware(true); 

を設定しました例

名前空間対応のDOMでは、getElementsByTagNameNSを使用するようにgetElementsByTagName呼び出しを変更する必要があります。

関連する問題