문제

LXML의 Etree로 생성하는 XML 문서에 DocTypes를 추가하고 싶습니다.

그러나 DocType를 추가하는 방법을 알 수 없습니다. 문자열을 하드 코딩하고 구입하는 것은 옵션이 아닙니다.

나는 Etree에서 Pi가 어떻게 추가되는지에 따라 무언가를 기대하고있었습니다.

pi = etree.PI(...)
doc.addprevious(pi)

그러나 그것은 나를 위해 일하지 않습니다. LXML로 XML 문서에 A를 추가하는 방법은 무엇입니까?

도움이 되었습니까?

해결책

DocType로 문서를 만들 수 있습니다.

# Adapted from example on http://codespeak.net/lxml/tutorial.html
import lxml.etree as et
import StringIO
s = """<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "cheese"> 
<!ENTITY eacute "&#233;"> ]>
<root>
<a>&tasty; souffl&eacute;</a>
</root>
"""
tree = et.parse(StringIO.StringIO(s))
print et.tostring(tree, xml_declaration=True, encoding="utf-8")

인쇄물:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE root SYSTEM "test" [
<!ENTITY tasty "cheese">
<!ENTITY eacute "&#233;">
]>
<root>
<a>cheese soufflé</a>
</root>

하나로 생성되지 않은 일부 XML에 DocType를 추가하려면 먼저 원하는 DocType (위와 같이)로 하나를 만들 수 있습니다.

xml = et.XML("<root><test/><a>whatever</a><end_test/></root>")
root = tree.getroot()
root[:] = xml
root.text, root.tail = xml.text, xml.tail
print et.tostring(tree, xml_declaration=True, encoding="utf-8")

인쇄물:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE root SYSTEM "test" [
<!ENTITY tasty "cheese">
<!ENTITY eacute "&#233;">
]>
<root><test/><a>whatever</a><end_test/></root>

그게 당신이 찾고있는 것입니까?

다른 팁

이것은 나를 위해 효과가있었습니다.

print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")

PI는 실제로 "DOC"의 이전 요소로 추가됩니다. 따라서 "Doc"의 자녀가 아닙니다. "doc.getRootTree ()"를 사용해야합니다.

예는 다음과 같습니다.

>>> root = etree.Element("root")
>>> a  = etree.SubElement(root, "a")
>>> b = etree.SubElement(root, "b")
>>> root.addprevious(etree.PI('xml-stylesheet', 'type="text/xsl" href="my.xsl"'))
>>> print etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='utf-8')
<?xml version='1.0' encoding='utf-8'?>
<root>
  <a/>
  <b/>
</root>

getRootTree () :

>>> print etree.tostring(root.getroottree(), pretty_print=True, xml_declaration=True, encoding='utf-8')
<?xml version='1.0' encoding='utf-8'?>
<?xml-stylesheet type="text/xsl" href="my.xsl"?>
<root>
  <a/>
  <b/>
</root>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top