2017-02-24 38 views
0

嘗試構建xml並注入包含許多元素的字符串。但是,通過做下面的錯誤,並不知道什麼是錯的。將XML內容注入標記時出現Python錯誤

from lxml import etree 
from lxml.builder import E as e 

list = ["one", "two", "three", "four", "five"] 

fields = "".join("<field>{}</field>".format(x) for x in list) 

xml = page = (
e.req(
    e.tab(
    e.fields(
     etree.fromstring(fields) 
    ) 
) 
) 
) 

錯誤:

lxml.etree.XMLSyntaxError: Extra content at the end of the document, line 1, column 20 

蟒(2.7.10) LXML(3.7.3)

回答

1

XML文件must have a single top-level root element,但你試圖從名單解析<field> s(爲了便於閱讀,添加了換行符):

<field>one</field> 
<field>two</field> 
<field>three</field> 
<field>four</field> 
<field>five</field> 

如果換那些根元素它應該工作:

<fields> 
    <field>one</field> 
    <field>two</field> 
    <field>three</field> 
    <field>four</field> 
    <field>five</field> 
</fields> 
+0

感謝現在的工作! – bogumbiker