XML 파싱

../_images/33888714601_a1f7d020a2_k_d.jpg

untangle

untangle 는 XML 문서를 받아 그 구조의 노드와 어트리뷰트를 그대로 반영한 파이썬 객체를 반환하는 간단한 라이브러리입니다.

예를 들어 다음과 같은 XML 파일이 있다고 합시다:

<?xml version="1.0"?>
<root>
    <child name="child1">
</root>

다음과 같이 로드할 수 있습니다:

import untangle
obj = untangle.parse('path/to/file.xml')

그러면 다음과 같이 자식 엘리먼트의 name 어트리뷰트를 가져올 수 있습니다:

obj.root.child['name']

untangle은 문자열이나 URL로부터 XML을 로드하는 것도 지원합니다.

xmltodict

xmltodict 은 XML을 JSON으로 작업하는 것처럼 느끼게 해주는 또 다른 간단한 라이브러리입니다.

다음과 같은 XML 파일을:

<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>

다음과 같이 파이썬 딕셔너리로 로드할 수 있습니다:

import xmltodict

with open('path/to/file.xml') as fd:
    doc = xmltodict.parse(fd.read())

그러면 다음과 같이 엘리먼트, 어트리뷰트, 값에 접근할 수 있습니다:

doc['mydocument']['@has'] # == u'an attribute'
doc['mydocument']['and']['many'] # == [u'elements', u'more elements']
doc['mydocument']['plus']['@a'] # == u'complex'
doc['mydocument']['plus']['#text'] # == u'element as well'

xmltodict은 unparse 함수로 다시 XML로 변환하는 라운드트립도 지원하며, 메모리에 다 들어가지 않는 파일을 처리하기에 적합한 스트리밍 모드를 가지고 있고, XML 네임스페이스도 지원합니다.

xmlschema

xmlschema 는 파이썬에서 XSD-Schema를 사용할 수 있도록 지원합니다. 다른 XML 라이브러리와는 달리 자동 타입 파싱이 가능하기 때문에, 예를 들어 스키마에서 어떤 엘리먼트의 타입을 int 로 정의하면 파싱된 dict 에도 해당 엘리먼트의 값이 int 로 들어있게 됩니다. 또한 이 라이브러리는 스키마에 따른 XML 문서의 자동 검증 및 명시적 검증을 지원합니다.

from xmlschema import XMLSchema, etree_tostring

# load a XSD schema file
schema = XMLSchema("your_schema.xsd")

# validate against the schema
schema.validate("your_file.xml")

# or
schema.is_valid("your_file.xml")

# decode a file
data = schmema.decode("your_file.xml")

# encode to string
s = etree_tostring(schema.encode(data))