【问题标题】:How to change tags with lxml in Python?如何在 Python 中使用 lxml 更改标签?
【发布时间】:2021-07-15 14:42:03
【问题描述】:

我想在 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"

有什么想法吗?

【问题讨论】:

标签: python xml lxml


【解决方案1】:

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

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

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

这里的.//p 表示lxml 也会搜索嵌套的p 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    相关资源
    最近更新 更多