2012-11-02 4 views
4

나는 그들이 양식에있을 때 DOM과 XML 문서를 구문 분석하는 방법을 알고 :얻기 값은

<tagname> valueIWant </tagname> 

그러나, 지금 얻으려고 요소는 형태로 대신하다

<photo farm="9" id="8147664661" isfamily="0" isfriend="0" ispublic="1" 
     owner="[email protected]" secret="4902a217af" server="8192" title="Rainbow"/> 

대개 값을 반환하려면 보통 cel.getTextContent()을 사용하지만이 경우에는 작동하지 않습니다. 어느 쪽도 작동하지 않을 것이라고 생각하는 cel.getAttributes()도 없습니다 ...

이상적으로, 저는 id와 owner 수치 값을 얻을 필요가 있습니다. 그러나 누군가가 그 모든 것을 얻는 방법을 도울 수 있다면, 나는 나중에 원하지 않는 부분을 제거 할 수 있습니다.

+0

이것은 특정 언어로는 반드시 유효한 형식은 아니지만 일반적으로 xml이 일반적으로 구조화되는 경향이 있음을 반영합니다.'string nine = doc.attributes [ "farm"]' –

답변

1

검색하려는 내용은 요소와 연결된 여러 속성의 값입니다. 이 목표를 달성하기 위해 getAttribute(String name) 메서드를 사용하십시오.

모든 특성을 검색하려면 getAttributes()을 사용하여 검색하고 반복 할 수 있습니다. 같은

private void getData(Document document){ 
    if(document == null) 
     return; 

    NodeList list = document.getElementsByTagName("photo"); 
    Element photoElement = null; 

    if(list.getLength() > 0){ 
     photoElement = (Element) list.item(0); 
    } 

    if(photoElement != null){ 
     System.out.println("ID: "+photoElement.getAttribute("id")); 
     System.out.println("Owner: "+photoElement.getAttribute("owner")); 

     NamedNodeMap childList = photoElement.getAttributes(); 
     Attr attribute; 

     for(int index = 0; index < childList.getLength(); index++){ 
      if(childList.item(index).getNodeType() == Node.ATTRIBUTE_NODE){ 
       attribute = ((Attr)childList.item(index)); 
       System.out.println(attribute.getNodeName()+" : "+attribute.getNodeValue()); 
      }else{ 
       System.out.println(childList.item(index).getNodeType()); 
      } 
     } 
    } 
} 
+0

Brilliant, charm. 감사! – user1766153

+0

@ user1766153 : 도와 줘서 기쁩니다. 나는 특정 속성 또는 모든 속성을 동시에 검색하는 방법에 대한 예제를 제공하기 위해 내 대답을 업데이트했습니다. 희망이뿐만 아니라 도움이 :) – Sujay

0

뭔가 :

Element photo = (Element)yournode; 
photo.getAttribute("farm"); 

는 당신에게 농장 속성의 값을 얻을 것이다 이러한 방법 모두의 예는 다음과 같이 될 수 있습니다. 이러한 속성에 액세스하려면 노드를 요소로 처리해야합니다 (doc).