簡體   English   中英

如何使用Python的lxml.objectify創建一個非嵌套的xml元素?

[英]How do you create a non-nested xml element using Python's lxml.objectify?

我目前的代碼是

xml_obj = lxml.objectify.Element('root_name')
xml_obj[root_name] = str('text')
lxml.etree.tostring(xml_obj)

但是這會創建以下xml:

<root_name><root_name>text</root_name></root_name>

在我使用它的應用程序中,我可以輕松地使用文本替換來解決這個問題,但知道如何使用庫來做它會很好。

我不熟悉objectify ,但我認為這不是它的用途。 它表示對象的方式是,任何給定級別的節點都是一個類名,子節點是字段名(帶有類型)和值。 而使用它的正常方式更像是這樣的:

xml_obj = lxml.objectify.Element('xml_obj')
xml_obj.root_path = 'text'
etree.dump(xml_obj)
<root_name xmlns:py="http://codespeak.net/lxml/objectify/pytype" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" py:pytype="TREE">
  <root_name py:pytype="str">text</root_name>
</root_name>

你想要的是使用etree更容易做到的etree

xml_obj = lxml.etree.Element('root_path')
xml_obj.text = 'text'
etree.dump(xml_obj)
<root_path>text</root_path>

如果你真的需要它是objectify ,看起來你不應該直接混合,你可以使用tostring生成XML,然后objectify.fromstring將它帶回來。 但可能,如果這是你想要的,你應該只使用etree來生成它。

我認為你不能將數據寫入根元素。 您可能需要創建一個這樣的子元素:

xml_obj = lxml.objectify.Element('root_name')
xml_obj.child_name = str('text')
lxml.etree.tostring(xml_obj)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM