2017-12-29 20 views
-1

xpath 쿼리가 작동하지 않아 몇 시간 동안 솔루션을 찾을 수 없습니다. 모든 도움에 감사드립니다. 표현을위한 이전의 시도xpath 쿼리 결과가 없습니다.

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()); 
     } 
} 

부 :

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

그들은 https://www.freeformatter.com/xpath-tester.html#ad-output에서 작동하지만 내 자바 코드이다. 나는 다음과 같은 라인을 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); 

절대적으로 아무 생각. prefix가 NamespaceContext에서 네임 스페이스 URI 세트와 일치하지 않는 경우

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

결과가 반환되지 않습니다 일반적으로

+1

요소가 정의 된 네임 스페이스에 존재하므로 요소를 정의해야합니다. –

0

은 실제로 부하의 XPath 엔진과 사용의 XPath 버전,하지만에 따라 달라집니다. 그래서 당신이 그것을 설정 한 - 그것은 작동합니다.

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

뿐만 아니라

String expression ="/*/*:id"

모두 serviceSpecificationid 및 (또는 searchElementsXml[j])는 어떤 네임 스페이스를 검색해야한다고 정의한다. - XPath 엔진 및 버전에 속합니다 - 지원되는 경우 작동합니다.

참고 : XPath 1.0은 "임의의 네임 스페이스"를 /*:element으로 지원하지 않습니다. XPath 2 이상. 아마도, 사용하는 엔진이 XPath 표현식을 XPath 1.0으로 위협합니다.