2011-02-16 3 views
1

파이썬에서는 xml을 파싱하고 싶지만 문자열에서는 파일에서 가져 오지 않습니다. 누군가 나를 도와 줄 수 있습니까?python parse xml text

답변

8

, 당신은 일반적으로 문자열을

from xml.dom import minidom           
xmldoc = minidom.parse('~/diveintopython/common/py/kgp/binary.xml') 

로 할 수있는, 당신은 당신이 사용할 수있는

from xml.dom import minidom           
xmldoc = minidom.parseString(Your string goes here) 
+0

는 너무 감사합니다 – rach

3

당신은 사용할 수 있습니다 xml.dom.minidom.parseString(text)

이 방법은 문자열의있는 StringIO 객체를 만들고에 구문 분석하는 것을()에 전달합니다.

파일 유사 개체가 필요한 다른 XML 구문 분석기에도 StringIO를 사용하는 것과 동일한 기술을 사용할 수도 있습니다.

파일에서
import StringIO 
your_favourite_xml_parser.parse(StringIO.StringIO('<xml>...</xml>')) 
2

(xml.etree.cElementTree)으로 변경할 수 있습니다 또한.

import xml.etree.cElementTree as ET 

aElement = ET.fromstring('<Root id="UUID_1"><Item id="id_Item" /></Root>') 

See Python help document 
Each element has a number of properties associated with it: 
    a tag which is a string identifying what kind of data this element represents (the element type, in other words). 
    a number of attributes, stored in a Python dictionary. 
    a text string. 
    an optional tail string. 
    a number of child elements, stored in a Python sequence 
1

lxml을 사용할 수도 있습니다. 시작 (http://dealites.com)에는 매일 많은 XML 처리가 필요합니다. 거의 모든 xml 라이브러리를 파이썬에서 사용할 수 있습니다. lxml은 xml 처리에 사용할 수있는 최상의 라이브러리입니다.

아름다운 스프를 사용해 볼 수도 있습니다. HTML 구문 분석에는 적합하지만 lxml에 대한 좋은 대안입니다.

LXML 예 :

from lxml import etree; 

parsedfeed = etree.xml('your xml here'); 

아름다운 수프 예 :

from BeautifulSoup import BeautifulStoneSoup; 

soup = BeautifulStoneSoup('your xml here');