2012-02-02 3 views
2

어떻게 내가 2 "C"태그의 값을 얻기 위해 자바 XPath는 사용 방법이자바 XPath는 쿼리

<a> 
    <b> 
     <c type="lol"> 
      <d>1</d> 
      <f>2</f> 
     </c> 
     <c type="lol"> 
      <d>2</d> 
      <f>2</f> 
     </c> 
      <c type="h"> 
      <d>v</d> 
      <f>d</f> 
     </c> 
    </b> 
</a> 

{ 
    DocumentBuilderFactory dBFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dB = dBFactory.newDocumentBuilder(); 
    Document doc = dB.parse(url);  
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 
    XPathFactory factory = XPathFactory.newInstance(); 
    XPath xpath = factory.newXPath(); 
    XPathExpression expr=null; 
    String text= null; 
    expr= xpath.compile("//a/b/c[@type='lol']/d/text()");// this gets the first value 
    text = (String) expr.evaluate(doc, XPathConstants.STRING); 
    } 

로 2 "C"태그 D와 F의 값을 얻기 위해 자바 XPath는 사용할 수 있습니다 D와 F 2

+0

귀하의 질문은 팅겨 또는 두 사람과 함께 할 수있는 -는 XML ENDTAG가 잘못하고 샘플 XPath는 대신 D의 "b"를 말한다. 좋은 대답은 아래, 그래도, 나는 오늘 뭔가를 배웠다] – davidfrancis

답변

5

사용과 같이

//a/b/c[@type='lol'][2]/d/text() 
+0

고마워, 나 자신도 해결책을 찾았 어....... 내 솔루션을 추가하기 위해 왔어, u (@ Kirill) 이미 솔루션을 넣었 어. –

+0

@tharanidharan, 환영. –