2017-12-29 42 views
-1

私のxpathクエリが機能せず、何時間も解決策が見つかりません。私はあらゆる助けに感謝しています。xpathクエリの結果がありません

String expression ="/*/" + prefix + ":" + searchElementsXml[j]; 
String expression ="/*:serviceSpecification" "/*:" + searchElementsXml[j]; 
String expression ="/*/*:id" 

彼らはhttps://www.freeformatter.com/xpath-tester.html#ad-outputではなく、私のJavaコードで働く:発現させるための以前の試みの

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
dbf.setNamespaceAware(true); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
InputSource inputSource = new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))); 
Document xmldocument = db.parse(inputSource); 
XPath xPath = XPathFactory.newInstance().newXPath(); 
String prefix = xmldocument.getDocumentElement().getPrefix(); 
searchElementsXml = new String[]{"name", "id", "version", "description", "keywords", "authorInfos.name", "status"}; 

for(int j = 0; j < searchElementsXml.length; j++){ 
    String expression ="/*/" + prefix + ":" + searchElementsXml[j]; 
    NodeList nodeList = (NodeList) 
    xPath.compile(expression).evaluate(xmldocument, XPathConstants.NODESET); 
     for (int i = 0; i < nodeList.getLength(); i++) {          
     System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
     } 
} 

パート。私は次の行をadedいる

<?xml version="1.0" encoding="UTF-8"?> 
<ServiceSpecificationSchema:serviceSpecification xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ServiceSpecificationSchema="http://foo.bar/ServiceSpecificationSchema.xsd" xsi:schemaLocation="http://foo.barServiceSpecificationSchema.xsd ServiceSpecificationSchema.xml"> 
    <ServiceSpecificationSchema:id>someid</ServiceSpecificationSchema:id> 
    <ServiceSpecificationSchema:name>myname</ServiceSpecificationSchema:name> 
.... 
+1

バージョンで閉じられたxml-name要素の例でエラーがあります。 – Michal

+0

ありがとうございます。パーツのコピー中にエラーが発生し、元のコードには存在しません。私はそれを調整している。 他に解決策がありますか? – Simon

答えて

0

:よう

私のXMLを見て、これは働いているが、今の私のクエリが動作する理由

SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext(); 
         simpleNamespaceContext.bindNamespaceUri(prefix,uri); 
         xPath.setNamespaceContext(simpleNamespaceContext); 

全くアイデア。

+1

要素は定義されている名前空間に存在し、そのように修飾する必要があります。 –

0

一般的には、下っ端XPathエンジンに依存し、あなたが使用するXPathバージョンが、実際:prefixはURIがNamespaceContextに設定された名前空間と一致しない場合

String expression ="/*/" + prefix + ":" + searchElementsXml[j];

は結果を返しません。だから、あなたがそれをセットアップした後、それは動作します。

String expression ="/*:serviceSpecification" "/*:" + searchElementsXml[j];

ならびに

String expression ="/*/*:id"

serviceSpecificationid(又はsearchElementsXml[j])は、任意の名前空間のために検索されなければならないことを定義両方。 - XPathエンジンとバージョンに属しています - サポートされていれば動作します。

注:XPath 1.0は、 "any namespace"を/*:elementとしてサポートしていません。 XPath 2+はそうです。 おそらく、使用しているエンジンがXPath式としてXPath式を脅かしています

関連する問題