2014-04-08 1 views
1

파이썬과 엘리먼트 트리를 사용하여 XML을 텍스트 항목으로 파싱하는 데 어려움을 겪고 있습니다. 각 광고 항목은 결국 데이터베이스에서 하나의 레코드가되어 사용자는 해당 필드 내의 여러 용어를 검색 할 수 있습니다. 샘플 XML :파이썬 요소 트리를 사용하여 xml을 파이썬으로 구문 분석

?xml version="1.0" encoding="utf-8"?> 
<root> 
    <mainTerm> 
     <title>Meat</title> 
     <see>protein</see> 
    </mainTerm> 
    <mainTerm> 
     <title>Vegetables</title> 
     <see>starch</see> 
    </mainTerm> 
    <mainTerm> 
     <title>Fruit</nemod></title> 
     <term level="1"> 
     <title>Apple</title> 
     <code>apl</code> 
     </term> 
     <term level="1"> 
     <title>Red Delicious</title> 
     <code>rd</code> 
     <term level="2"> 
      <title>Large Red Delicious</title> 
      <code>lrd</code> 
     </term> 
     <term level="2"> 
      <title>Medium Red Delicious</title> 
      <code>mrd</code> 
     </term> 
     <term level="2"> 
      <title>Small Red Delicious</title> 
      <code>mrd</code> 
     </term>   
     <term level="1"> 
     <title>Grapes</title> 
     <code>grp</code> 
     </term> 
     <term level="1"> 
     <title>Peaches</title> 
     <code>pch</code> 
     </term>  
    </mainTerm> 
</root> 

원하는 출력 :

Meat > protein 
Vegetables > starch 
Fruit > Apple > apl 
Fruit > Apple > apl > Red Delicious > rd 
Fruit > Apple > apl > Red Delicious > rd > Large Red Delicious > lrd 
Fruit > Apple > apl > Red Delicious > rd > Medium Red Delicious > mrd 
Fruit > Apple > apl > Red Delicious > rd > Small Red Delicious > srd 
Fruit > Grapes > grp 
Fruit > Peaches > pch 

그것은 XML을 구문 분석 태그 'mainTerm'를 사용하기에 충분 쉽지만, 까다로운 부분이에 하나 개의 수준 만에 각 행을 제한하고 텍스트에서 상위 레벨 용어도 포함하여 같은 시간. 기본적으로 텍스트의 고유 한 줄을 만들어서 XML 계층 구조를 "평평하게"하려합니다. 각 줄에는 부모 (예 : 과일> Apple> APL)가 있지만 형제 (예 : Large Red Delicious, Medium Red Delicious 또는 Small Red 맛있는).

이 작업은 먼저 데이터를 관계형 데이터베이스 형식으로 변환 한 다음 쿼리를 실행하여 수행 할 수 있음을 알고 있지만 XML에서 직접 직접 솔루션을 원합니다. 이 의미를 만들어

희망 ... 감사

+0

당신이 제공하신 XML이 잘 형성되지 않습니다 : : 몇 가지 변화가 잘 형성하기 위해 함께, 그것은 인쇄) 내 의견을 참조, 이상한''태그를 볼 수 없음 닫는 ''태그. – alecxe

답변

1

바로 XML를 벗어난 계층 적 데이터 구조를 만드는 xmltodict라는 좋은 도구가 :

import json 
import xmltodict 


data = """your xml goes here""" 

result = xmltodict.parse(data) 
print(json.dumps(result, indent=4)) 

당신이 제공 한 XML의 경우는 (

{ 
    "root": { 
     "mainTerm": [ 
      { 
       "title": "Meat", 
       "see": "protein" 
      }, 
      { 
       "title": "Vegetables", 
       "see": "starch" 
      }, 
      { 
       "title": "Fruit", 
       "term": [ 
        { 
         "@level": "1", 
         "title": "Apple", 
         "code": "apl" 
        }, 
        { 
         "@level": "1", 
         "title": "Red Delicious", 
         "code": "rd", 
         "term": [ 
          { 
           "@level": "2", 
           "title": "Large Red Delicious", 
           "code": "lrd" 
          }, 
          { 
           "@level": "2", 
           "title": "Medium Red Delicious", 
           "code": "mrd" 
          }, 
          { 
           "@level": "2", 
           "title": "Small Red Delicious", 
           "code": "mrd" 
          } 
         ] 
        }, 
        { 
         "@level": "1", 
         "title": "Grapes", 
         "code": "grp" 
        }, 
        { 
         "@level": "1", 
         "title": "Peaches", 
         "code": "pch" 
        } 
       ] 
      } 
     ] 
    } 
} 
+0

답장을 보내 주셔서 감사합니다. 그러나 각 레벨마다 한 줄 씩 (">"기호로 구분 된 상위 레벨의 텍스트가 있음). 또는 XML을 JSON으로 변환 했는지도 모르겠지만 PHP/SQL 대신 JavaScript/JSON을 통해 데이터를 검색 할 수는 있지만 훨씬 덜 효율적이라고 생각합니다. – user1526973

+0

@ user1526973 예, 여기가 실제로 요점입니다. 더 쉽게 작업 할 수있는 것으로 변환하십시오. 희망이 도움이됩니다. – alecxe