파이썬을 사용하여 간단한 XML 파일 만들기
파이썬으로 간단한 XML 파일을 만들려면 어떻게해야합니까? (라이브러리 현명한)
내가 원하는 XML은 다음과 같습니다.
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some vlaue2</field2>
</doc>
</root>
요즘 가장 인기 있고 매우 간단한 옵션은 ElementTree API 이며, Python 2.5 이후 표준 라이브러리에 포함되었습니다.
사용 가능한 옵션은 다음과 같습니다.
- ElementTree (ElementTree의 기본 순수 Python 구현. 2.5 이후 표준 라이브러리의 일부)
- cElementTree (ElementTree의 최적화 된 C 구현. 2.5 이후 표준 라이브러리에서도 제공됨)
- LXML (libxml2 기반. XPath, CSS 선택기 등 ElementTree API의 풍부한 수퍼 세트를 제공함)
다음은 in-stdlib cElementTree를 사용하여 예제 문서를 생성하는 방법에 대한 예입니다.
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")
나는 그것을 테스트하고 작동하지만 공백이 중요하지 않다고 가정합니다. "prettyprint"들여 쓰기가 필요한 경우 알려 주시면 어떻게해야하는지 찾아 보겠습니다. (LXML 관련 옵션 일 수 있습니다. stdlib 구현을 많이 사용하지 않습니다)
추가로 읽을 수있는 유용한 링크는 다음과 같습니다.
- Python 표준 라이브러리의 구현을위한 API 문서
- 입문 자습서 (원본 저자의 사이트에서)
- LXML etree 튜토리얼 . (모든 주요 ElementTree 구현에서 최상의 옵션을로드하기위한 예제 코드 포함)
마지막으로, cElementTree 또는 LXML은 모든 요구에 맞게 충분히 빨라야합니다 (둘 다 최적화 된 C 코드 임). 그러나 성능의 모든 마지막 부분을 짜야하는 상황에서는 벤치 마크 LXML 사이트는 다음을 나타냅니다.
- LXML이 XML 직렬화 (생성)에서 분명히 승리
- 적절한 부모 순회를 구현하는 부작용으로 LXML은 cElementTree보다 약간 느리게 구문 분석됩니다.
lxml이 라이브러리는 호출 된 XML 생성을위한 매우 편리한 구문이 포함되어 E-공장 . 다음은 내가 제시 한 예를 만드는 방법입니다.
#!/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/ or https://github.com/leforestier/yattag provides an interesting API to create such XML document (and also HTML documents).
It's using context manager and with
keyword.
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)
so you will get:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
For the simplest choice, I'd go with minidom: http://docs.python.org/library/xml.dom.minidom.html . It is built in to the python standard library and is straightforward to use in simple cases.
Here's a pretty easy to follow tutorial: http://www.boddie.org.uk/python/XML_intro.html
For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates
For a Jinja example, see my answer to a similar question.
Here is an example of generating your xml with string templates.
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
Output:
<root>
<doc>
<field1 name="foo">The value for the foo document</field1>
<field2 name="bar">The <value> for the <bar> document</field2>
</doc>
</root>
The downer of the template approach is that you won't get escaping of <
and >
for free. I danced around that problem by pulling in a util from xml.sax
I just finished writing an xml generator, using bigh_29's method of Templates ... it's a nice way of controlling what you output without too many Objects getting 'in the way'.
As for the tag and value, I used two arrays, one which gave the tag name and position in the output xml and another which referenced a parameter file having the same list of tags. The parameter file, however, also has the position number in the corresponding input (csv) file where the data will be taken from. This way, if there's any changes to the position of the data coming in from the input file, the program doesn't change; it dynamically works out the data field position from the appropriate tag in the parameter file.
Tags and value need to be used preceliey and to the point for this to work. I done this before i will find my code to show as example.
한편 더 많은 정보를 찾을 수 있습니다 여기 - https://www.w3schools.com/php/
참고 URL : https://stackoverflow.com/questions/3605680/creating-a-simple-xml-file-using-python
'Programing' 카테고리의 다른 글
파이썬에서 디스크에 기본 http 파일 다운로드 및 저장? (0) | 2020.06.20 |
---|---|
배치 파일에서 변수로 파일 내용을 읽는 방법은 무엇입니까? (0) | 2020.06.20 |
if-else 블록에서 'if (0)'블록의 목적은 무엇입니까? (0) | 2020.06.20 |
Android Facebook 4.0 SDK 이메일, 생년월일 및 사용자 성별을 얻는 방법 (0) | 2020.06.20 |
메소드 매개 변수의 최종 키워드 (0) | 2020.06.20 |