【问题标题】:lxml how to append a new element and its value to node?lxml如何将新元素及其值附加到节点?
【发布时间】:2021-05-07 17:02:26
【问题描述】:

我有一个 xml:

<?xml version="1.0" encoding="UTF-8"?>
 - <note>
       <to>Tove</to>
       <from>Jani</from>
       <heading>Reminder</heading>
       <body>Don't forget me this weekend!</body>
   </note>

现在我想在note下添加一个id元素和它的值,输出应该是这样的:

<?xml version="1.0" encoding="UTF-8"?>
 - <note>
       <id>3</id>
       <to>Tove</to>
       <from>Jani</from>
       <heading>Reminder</heading>
       <body>Don't forget me this weekend!</body>
   </note>

有朋友可以帮忙吗?

【问题讨论】:

  • 你尝试了什么?你的代码在哪里?你检查是否有 insert() ?你收到错误信息了吗?始终将有问题的完整错误消息(从“Traceback”一词开始)(不是评论)作为文本(不是屏幕截图,不是指向外部门户的链接)。还有其他有用的信息。
  • &lt;note&gt; 之前有- 吗?它可能是不正确的 XML,lxml 读取有问题。

标签: python python-3.x xml lxml


【解决方案1】:

如果您有没有- 的xml,那么它将是有效的xml,并且可以与lxml 一起使用

您可以使用Element() 创建新元素

import lxml.etree as ET

item = ET.Element('id')
item.text = '3'
item.tail = '\n       '  # to format indentation

然后你可以使用element.insert(position, new_element)

tree = ET.fromstring(text.encode('utf-8'))

note = tree
#note = tree.find('note')

note.insert(0, item)

最少的工作代码(没有-

text = '''<?xml version="1.0" encoding="UTF-8"?>
<note>
       <to>Tove</to>
       <from>Jani</from>
       <heading>Reminder</heading>
       <body>Don't forget me this weekend!</body>
</note>
'''

import lxml.etree as ET

tree = ET.fromstring(text.encode('utf-8'))

note = tree
#note = tree.find('note')

item = ET.Element('id')
item.text = '3'
item.tail = '\n       '

note.insert(0, item)

text = ET.tostring(tree, xml_declaration=True, encoding='UTF-8').decode()

print(text)

结果:

<?xml version='1.0' encoding='UTF-8'?>
<note>
       <id>3</id>
       <to>Tove</to>
       <from>Jani</from>
       <heading>Reminder</heading>
       <body>Don't forget me this weekend!</body>
</note>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多