将属性值附加到元素使用lxml

huangapple go评论61阅读模式
英文:

append attribute value to element using lxml

问题

我在这里或在lxml文档中都找不到任何信息。

我有一个已经有属性的元素,我只需将一个值附加到该现有属性上。如果我尝试使用myelement.set('animals', 'dog'),那么在这个示例中的属性animal会被覆盖。如何在现有属性上附加另一个值的技巧是什么。

现有元素的示例:<para animals="cat" />

我最终想要实现的目标是:<para animals="cat dog" />

虽然我可以将其转换为字符串,执行此操作,然后重新编码它并替换元素,但这似乎不是正确的做法。有什么建议吗?

英文:

I can't find anything either here or in the lxml documentation.

I have an element which has an attribute already, I simply need to append a value to that existing attribute. If I try to use myelement.set(&#39;animals&#39;, &#39;dog&#39;), then the attribute animal in this example is overwritten. What is the trick to append another value to existing attribute.

Example of existing element: &lt;para animals=&quot;cat&quot; /&gt;

What I ultimately want to achieve would be: &lt;para animals=&quot;cat dog&quot; /&gt;

While I could turn this into a string, perform this operation, then reencode it and replace the element, that just doesn't feel like the right way to do this. Any ideas?

答案1

得分: 1

import xml.etree.ElementTree as ET
from io import StringIO

xml_str = """<root><para animals="cat" /></root>"""

f = StringIO(xml_str)

tree = ET.parse(f)
root = tree.getroot()

for elem in root.iter():
    if elem.tag == "para":
        elem.set("animals", elem.get('animals') + " dog")

ET.dump(root)

输出:

<root><para animals="cat dog" /></root>
英文:

You would like to change only the string of the element attribute:

import xml.etree.ElementTree as ET
from io import StringIO

xml_str=&quot;&quot;&quot;&lt;root&gt;&lt;para animals=&quot;cat&quot; /&gt;&lt;/root&gt;&quot;&quot;&quot;

f = StringIO(xml_str)

tree = ET.parse(f)
root = tree.getroot()

for elem in root.iter():
    if elem.tag == &quot;para&quot;:
        elem.set(&quot;animals&quot; , elem.get(&#39;animals&#39;)+&quot; dog&quot;)

ET.dump(root)

Output:

&lt;root&gt;&lt;para animals=&quot;cat dog&quot; /&gt;&lt;/root&gt;

huangapple
  • 本文由 发表于 2023年7月7日 02:48:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76631749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定