2009-06-14 25 views
11

Tôi muốn thêm các loại tài liệu vào tài liệu XML mà tôi đang tạo bằng etree của LXML.Tạo một loại tài liệu với etx của lxml

Tuy nhiên tôi không thể tìm ra cách thêm loại tài liệu. Hardcoding và concating chuỗi không phải là một lựa chọn.

Tôi đã chờ đợi một cái gì đó dọc theo dòng về cách PI được thêm vào etree:

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

Nhưng nó không làm việc cho tôi. Làm thế nào để thêm một tài liệu xml với lxml?

Trả lời

8

Bạn có thể tạo tài liệu của bạn với một loại tài liệu để bắt đầu với:

# 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") 

in:

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

Nếu bạn muốn thêm một loại tài liệu được cho một số XML mà không được tạo ra với một, trước tiên, bạn có thể tạo một tài liệu với loại tài liệu mong muốn (như trên), sau đó sao chép XML không có doctype của bạn vào:

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") 

in:

<?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> 

Đó có phải là những gì bạn đang tìm kiếm không?

+0

Liên kết đã lỗi thời. –

4

PI thực sự được thêm làm phần tử trước đó từ "doc". Vì vậy, nó không phải là một đứa trẻ của "doc". Bạn phải sử dụng "doc.getroottree()"

Dưới đây là một ví dụ:

>>> 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> 

với 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> 
+0

Đây phải là câu trả lời đúng. – Tom

26

này đã làm việc cho tôi:

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

+0

Giải pháp sạch hơn nhiều cho một cây đã tồn tại. Cảm ơn. – Khorkrak

Các vấn đề liên quan