programing

python을 사용하여 단순 XML 파일 만들기

goodcopy 2023. 1. 20. 16:30
반응형

python을 사용하여 단순 XML 파일 만들기

python으로 단순 XML 파일을 작성하려면 어떻게 해야 합니까?(대단히 현명하다)

원하는 xml은 다음과 같습니다.

<root>
 <doc>
     <field1 name="blah">some value1</field1>
     <field2 name="asdfasd">some vlaue2</field2>
 </doc>

</root>

오늘날 가장 일반적인(그리고 매우 간단한) 옵션은 Element입니다.Tree API - Python 2.5 이후 표준 라이브러리에 포함되어 있습니다.

사용 가능한 옵션은 다음과 같습니다.

  • ElementTree(ElementTree의 기본 순수 Python 구현).2.5 이후 표준 라이브러리의 일부)
  • 요소트리(ElementTree의 최적화된C 실장).2.5 이후 표준 라이브러리에서도 제공되고 있습니다.더 이상 사용되지 않고 일반 요소로 접힙니다.3.3 시점의 자동 트리)
  • LXML(libxml2에 기반).풍부한 요소의 슈퍼셋을 제공합니다.Tree API 및 XPath, CSS Selectors 등)

다음으로 in-stdlib cElement를 사용하여 샘플 문서를 생성하는 예를 나타냅니다.트리:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

테스트를 해봤는데 작동하긴 하지만 공백은 중요하지 않을 것 같아요."예쁜 인쇄" 들여쓰기가 필요한 경우 알려주시면 방법을 찾아보겠습니다(LXML 고유의 옵션일 수 있습니다).stdlib 실장은 잘 사용하지 않습니다.)

자세한 내용을 참조할 수 있도록 다음 링크를 참조하십시오.

마지막 메모로서 cElement 중 하나트리 또는 LXML은 모든 요구에 충분히 대응할 수 있는 속도여야 합니다(둘 다 최적화된 C 코드입니다).다만, 퍼포먼스의 마지막 비트를 모두 짜낼 필요가 있는 경우는, LXML 사이트의 벤치마크에 다음과 같이 표시됩니다.

  • LXML은 XML의 시리얼화(생성)에 확실히 성공
  • 적절한 부모 트래버설 구현의 부작용으로 LXML은 cElement보다 약간 느립니다.해석용 트리.

lxml 라이브러리에는 E-factory라고 불리는 매우 편리한 XML 생성 구문이 포함되어 있습니다.예를 들면 다음과 같습니다.

#!/usr/bin/python
import lxml.etree
import lxml.builder    

E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2

the_doc = ROOT(
        DOC(
            FIELD1('some value1', name='blah'),
            FIELD2('some value2', name='asdfasd'),
            )   
        )   

print lxml.etree.tostring(the_doc, pretty_print=True)

출력:

<root>
  <doc>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>
  </doc>
</root>

또, 이미 작성된 노드에의 추가도 서포트하고 있습니다.예를 들어, 상기의 경우는 다음과 같습니다.

the_doc.append(FIELD2('another value again', name='hithere'))

Yattag http://www.yattag.org/ 또는 https://github.com/leforestier/yattag은 이러한 XML 문서(HTML 문서도 포함)를 작성하기 위한 흥미로운 API를 제공합니다.

콘텍스트 매니저를 사용하여with키워드를 지정합니다.

from yattag import Doc, indent

doc, tag, text = Doc().tagtext()

with tag('root'):
    with tag('doc'):
        with tag('field1', name='blah'):
            text('some value1')
        with tag('field2', name='asdfasd'):
            text('some value2')

result = indent(
    doc.getvalue(),
    indentation = ' '*4,
    newline = '\r\n'
)

print(result)

다음과 같은 이점을 얻을 수 있습니다.

<root>
    <doc>
        <field1 name="blah">some value1</field1>
        <field2 name="asdfasd">some value2</field2>
    </doc>
</root>

가장 간단한 선택은 미니돔(http://docs.python.org/library/xml.dom.minidom.html)으로 하겠습니다.python 표준 라이브러리에 내장되어 있으며 간단한 경우에 사용하기 쉽습니다.

여기 튜토리얼이 있습니다.http://www.boddie.org.uk/python/XML_intro.html

이러한 단순한 XML 구조에서는 풀 블로잉 XML 모듈을 사용하지 않는 것이 좋습니다.가장 단순한 구조에는 문자열 템플릿을, 조금 더 복잡한 구조에는 Jinja를 고려해 보십시오.Jinja는 문서 목록의 내부 xml을 생성하기 위해 데이터 목록에 대한 루핑을 처리할 수 있습니다.raw python string templates는 조금 더 까다롭습니다.

Jinja의 예를 들자면, 비슷한 질문에 대한 제 대답을 보세요.

다음은 문자열 템플릿을 사용하여 xml을 생성하는 예입니다.

import string
from xml.sax.saxutils import escape

inner_template = string.Template('    <field${id} name="${name}">${value}</field${id}>')

outer_template = string.Template("""<root>
 <doc>
${document_list}
 </doc>
</root>
 """)

data = [
    (1, 'foo', 'The value for the foo document'),
    (2, 'bar', 'The <value> for the <bar> document'),
]

inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result

출력:

<root>
 <doc>
    <field1 name="foo">The value for the foo document</field1>
    <field2 name="bar">The &lt;value&gt; for the &lt;bar&gt; document</field2>
 </doc>
</root>

의 더 된 점은 어프로치가 입니다.< ★★★★★★★★★★★★★★★★★」>무료.나는 그 문제를 회피하기 위해 춤을 추었다.xml.sax

bigh_29의 Templates 메서드를 사용하여 xml 생성기를 방금 작성했습니다.너무 많은 개체가 '방해'되지 않고 출력 내용을 제어할 수 있는 좋은 방법입니다.

태그와 값에 대해서는 출력 xml 내의 태그 이름과 위치를 나타내는 어레이와 태그 목록이 동일한 파라미터 파일을 참조하는 어레이를 2개 사용했습니다.단, 파라미터 파일에는 데이터를 취득하는 대응하는 입력(csv) 파일 내의 위치 번호도 포함되어 있습니다.이와 같이 입력 파일에서 들어오는 데이터의 위치에 변경이 있어도 프로그램은 변경되지 않고 파라미터 파일의 적절한 태그에서 데이터 필드 위치를 동적으로 계산합니다.

언급URL : https://stackoverflow.com/questions/3605680/creating-a-simple-xml-file-using-python

반응형