繁体   English   中英

如何在 Python 中使用 lxml 更改标签?

[英]How to change tags with lxml in Python?

我想在 python 中使用 lxml 将所有标签名称<p>更改为<para>

这是 xml 文件外观的示例。

<concept id="id15CDB0Q0Q4G"><title id="id15CDB0R0VHA">General</title>
<conbody><p>This section</p></conbody>
<concept id="id156F7H00GIE"><title id="id15CDB0R0V1W">
System</title>
<conbody><p> </p>
<p>The 
</p>
<p>status.</p>
<p>sensors.</p>

我一直在尝试像这样编码它,但它没有找到带有 .findall 的标签。

from lxml import etree
doc = etree.parse("73-20.xml")
print("\n")

print(etree.tostring(doc, pretty_print=True, xml_declaration=True, encoding="utf-8"))
print("\n")

raiz = doc.getroot()
print(raiz.tag)
children = raiz.getchildren()
print(children)
print("\n")

libros = doc.findall("p")
print(libros)
print("\n")

for i in range(len(libros)):
    if libros[i].find("p").tag == "p" :
        libros[i].find("p").tag = "para"

有什么想法吗?

lxml findall()函数提供了按路径搜索的能力:

libros = raiz.findall(".//p")

for el in libros:
    el.tag = "para"

这里.//p意味着 lxml 也将搜索嵌套的p元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM