2011-08-16 2 views
0

JDOM을 사용하여 XML 파일을 구문 분석하고 모든 요소에서 일부 정보를 얻어야합니다.JDOM을 사용하여 XML 파싱을 자동화하는 방법

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <element1>something</element1> 
    <element2> 
     <subelement21>moo</subelement21> 
     <subelement22> 
      <subelement221>toto</subelement221> 
      <subelement222>tata</subelement222> 
     </subelement22> 
    </element2> 
</root> 

그래서 요소 1의 경우 쉽습니다. 그러나 요소 2의 경우 나는 그의 자녀들을 지나쳐야하며, 자녀들이 있다면 그들도 지나가도록해야합니다.

public static void getInfos(Vector<String> files) {  
    Document document = null; 
    Element root = null; 

    SAXBuilder sxb = new SAXBuilder(); 

    for (int i =0 ; i< files.size() ; i++) 
    { 
     System.out.println("n°" + i + " : " + files.elementAt(i)); 
     try 
     { 
      document = sxb.build(files.elementAt(i)); 
      root = document.getRootElement(); 

      List<?> listElements = root.getChildren(); 
      Iterator<?> it = listElements.iterator(); 

      while(it.hasNext()) 
      { 
       Element courant = (Element)it.next(); 
       System.out.println(courant.getName()); 

       if(courant.getChildren().size() > 0) 
       { 
        // here is the problem -> the element has a children 
       } 
      } 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

재귀 호출 또는 이와 비슷한 기능을 사용할 수 있도록이 경우 무엇을 제안합니까?

감사합니다.

답변

1

SAX를 사용합니다. 내 현재 경로가 문서에서 무엇인지 추적하는 contenthandler에 스택을 유지하고 내 문자 메소드가 추가 된 버퍼를 유지합니다. endElement에서 버퍼에서 내용을 가져와이를 지우고 현재 경로를 사용하여 처리 할 내용을 결정합니다.

(이는이 문서에는 복합 콘텐츠가 없다고 가정한다.)

여기에서는 I 간단히 재귀 데이터 구조를 처리하는 방식으로 설명한 것에 팽창, an article on using SAX to process complex XML documents에 대한 링크이다. (이전 제품 인 an introduction to SAX도 있습니다.)

0

XPath을 사용하면 원하는 요소를 정확하게 얻을 수 있습니다. 예제 here은 네임 스페이스를 사용하지만 기본 아이디어는 그대로 유지됩니다.

관련 문제