<elem1>
<elem2/>
<elem2 id="1234567"/>20,000 Leagues Under the Sea</elem1>
如果提供的 id 与使用 x
的列表项匹配,我一直在尝试从列表 lxml
插入字符串。问题是,我似乎找不到一种方法让它在父标签结束之前 </elem1>
。
示例字符串:
<elem3><elem4>book, item</elem4></elem3>
期望的输出:
<elem1>
<elem2/>
<elem2 id="1234567"/>20,000 Leagues Under the Sea<elem3><elem4>book, item</elem4></elem3></elem1>
.tail 函数可以做我想要的事情,但在标签的另一侧,而不是在标签内部。简单地将字符串附加到元素的 .text 在技术上是可行的,但它无法显示它,因为我想,在某些情况下,<elem2/>
标签会在开头,并且在这种情况之后,它通常会在循环的后续迭代中停止工作。
最佳答案
您需要count()
文档中的元素数量,然后insert(where, what)
:
books = """<elem1>
<elem2/>
<elem2 id="1234567"/>
20,000 Leagues Under the Sea
</elem1>
"""
doc = etree.fromstring(books)
newbies = """<elem3>
<elem4>book, item</elem4>
</elem3>
"""
elems = etree.fromstring(newbies)
destination = int(doc.xpath('count(//*)'))
#you need the int() because the output of count() is a float
#also remember that python counts from zero
doc.insert(destination,elems)
print(etree.tostring(doc).decode())
输出:
<elem1>
<elem2/>
<elem2 id="1234567"/>
20,000 Leagues Under the Sea
<elem3>
<elem4>book, item</elem4>
</elem3></elem1>
关于python - 在 XML 的结束标记之前插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73114308/