2012-01-19 2 views
1

내 프로그램에서 아래에 표시된 xml 파일을 다운로드하고 있습니다.JDOM/Jaxen을 사용하는 XPath 문제

작업은 모든 속성 통화 및 비율을 추출하는 데 매우 간단해야합니다. 나는 JDOM을 사용하고과 같이 시작

은 다음과 같습니다

try { 
    // TODO code application logic here 
    SAXBuilder builder = new SAXBuilder(); 
    org.jdom.Document doc = builder.build("test.xml"); 
    List<?> all = XPath.selectNodes(doc, "/Envelope/Cube/Cube/@currency"); 
    for(Object o : all) { 
     Attribute att = (Attribute) o; 
     System.out.println("ausgbabe: " + att); 
    } 
} 

이 항목을 얻기 위해 여러 경로를 테스트 한 적이 있지만 작동하지 않습니다.

<?xml version="1.0" encoding="UTF-8"?> 
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> 
    <gesmes:subject>Reference rates</gesmes:subject> 
    <gesmes:Sender> 
     <gesmes:name>European Central Bank</gesmes:name> 
    </gesmes:Sender> 
    <Cube> 
     <Cube time='2012-01-17'> 
      <Cube currency='USD' rate='1.2790'/> 
      <Cube currency='JPY' rate='98.20'/> 
      <Cube currency='BGN' rate='1.9558'/> 
      <Cube currency='CZK' rate='25.650'/> 
      <Cube currency='DKK' rate='7.4353'/> 
      <Cube currency='GBP' rate='0.83045'/> 
     </Cube> 
    </Cube> 
</gesmes:Envelope> 
+1

작동하지? – OrangeDog

답변

1

xml에 XPath 엔진에 대해 알려주지 않은 네임 스페이스가 있습니다. javax.xml.namespace.NamespaceContext을 사용해야합니다. 전체 설명 및 작동을위한 지침은 this article을 참조하십시오.

6

xpath 객체에 네임 스페이스를 바인딩해야합니다.

XPath xpath = XPath.newInstance("/gesmes:Envelope/root:Cube/root:Cube/root:Cube/@currency"); 

이 다음에 네임 스페이스 선언을 추가합니다 : 사실

xpath.addNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01"); 
xpath.addNamespace("root", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"); 

, 당신은 (난 당신의 XPath에 새로운 큐브 항목을 추가했다 )이 같은 XPath는 객체를 생성한다 Envelope 요소에는 "http://www.gesmes.org/xml/2002-08-01"네임 스페이스 URI가 있고 모든 큐브 요소에는 "http://www.ecb.int/vocabulary/2002-08- 01/eurofxref "네임 스페이스 URI, 기본 네임 스페이스로 선언되었습니다. xpath에서 원하는 네임 스페이스 접두어를 사용할 수 있지만 uri는 일치해야합니다.

List<?> all = xpath.selectNodes(doc); 

내가 당신의 XML이 코드를 테스트하고 다음과 같은 출력을 생성합니다 :
다음 당신이 만든 XPath를 사용하여이 같은 문서를 검색하는 방법을

ausgbabe: [Attribute: currency="USD"] 
ausgbabe: [Attribute: currency="JPY"] 
ausgbabe: [Attribute: currency="BGN"] 
ausgbabe: [Attribute: currency="CZK"] 
ausgbabe: [Attribute: currency="DKK"] 
ausgbabe: [Attribute: currency="GBP"] 
+0

실제로 코드를 변경 한 후에는 작동하지 않습니다. – Alanmars

+0

글쎄,이 코드를 사용하여 XML 시도하고 작동합니다. 내 대답에 출력을 추가했습니다. 코드 안에 세 조각을 모두 복사했는지 확인해 주시겠습니까? – javanna

+0

예, 작동합니다. 문제는 기본 네임 스페이스에서 발생합니다. @ javanna – Alanmars