英文:
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('animals', 'dog')
, then the attribute animal in this example is overwritten. What is the trick to append another value to existing attribute.
Example of existing element: <para animals="cat" />
What I ultimately want to achieve would be: <para animals="cat dog" />
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="""<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)
Output:
<root><para animals="cat dog" /></root>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论