2012-07-11 4 views
1

XPATH를 사용하여 네임 스페이스로 XML 문서를 구문 분석하려고합니다. 나는 그것이 어떻게 이루어져야하는지 읽었다. NamespaceContext도 구현했습니다. 그러나 나는 아직도 가치를 얻지 못하고있다. 나는 뭔가를 놓치고 있다고 생각한다.xpath와 Java 클래스의 네임 스페이스 사용

내 XML 입력이

<?xml version="1.0" encoding="UTF-8"?> 
<ns1:customer xmlns:ns1="http://test/ns1"> 
    <ns1:name>john</ns1:name> 
</ns1:customer> 

내 주요 파일 TestXMLPath

public static void main(String[] args) throws Exception { 

    String myInputXML = "src/testxmlpath/input-with-namespace.xml"; 
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();   

    String expression ="/ns1:customer/ns1:name"; 

    Document document = db.parse(new File(myInputXML)) ; 
    XPath xpath = XPathFactory.newInstance().newXPath(); 
    xpath.setNamespaceContext(new SimpleNamespaceContextImpl()); 
    String value = xpath.evaluate(expression,document); 
    System.out.println("value" + value); 
} 

내 NamespaceContext 구현은 메소드가 호출 될 때이 인쇄

public class SimpleNamespaceContextImpl implements NamespaceContext { 

@Override 
public String getNamespaceURI(String prefix) { 
    System.out.println("getNameSpace for prefix "+prefix);   
    if (prefix == null) {    
     throw new NullPointerException("Null prefix"); 
    } else if ("ns1".equals(prefix)) {    
     return "http://test/ns1"; 
    } else if ("xml".equals(prefix)) {    
     return XMLConstants.XML_NS_URI; 
    } else {    
     return XMLConstants.XML_NS_URI; 
    } 
} 

@Override 
public String getPrefix(String namespaceURI) {   
    return "ns1"; 
} 

@Override 
public Iterator getPrefixes(String namespaceURI) { 
    return null; 
} 
} 

이다. 다음은 결과입니다.

getNameSpace for prefix ns1 
getNameSpace for prefix ns1 
value 
BUILD SUCCESSFUL 

나는 이해할 수 없다.

도움이 될 것입니다.

감사합니다.

답변

1

저에게 잘 맞습니다. 출력 :

getNameSpace for prefix ns1 
getNameSpace for prefix ns1 
valuejohn 

올바른 문서를로드 하시겠습니까? Xerces를 사용하여 문서를 만들고 Saxon을 사용하여 XPath를 평가합니다. 관련 수업의 덤프 :

class com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl 
class com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl 
class net.sf.saxon.xpath.XPathFactoryImpl 
+1

나는 문제를 발견했다 !! 네임 스페이스를 인식 할 때 xml 파일에서 문서를 만들 때 문제가 발생하지 않았습니다. 변경 내용은 다음과 같습니다. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware (true); DocumentBuilder db = dbf.newDocumentBuilder(); – javakurious

+0

@ user1309197 - 아, 그래, 그건 의미가 있고 좋은 습관이다. * all * 파서로 설정할 필요가 없기 때문에 실행했을 때 효과가 있었지만 항상 그렇게하는 것이 좋습니다. –

+0

참고 : http://comments.gmane.org/gmane.text.xml.saxon.help/13298 –