如何用beauthoulsoup替换/删除XML标记?

2024-10-03 17:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个本地文件中有一个XML,它是一个最终消息的模板,该消息将POST编辑到REST服务。脚本在发布模板数据之前对其进行预处理。在

所以模板看起来像这样:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <singleElement>
        <subElementX>XYZ</subElementX>
    </singleElement>
    <repeatingElement id="11" name="Joe"/>
    <repeatingElement id="12" name="Mary"/>
</root>

消息XML的外观应该相同,只是repeatingElement标记需要替换为其他标记(由脚本根据现有标记中的属性生成的XML)。在

以下是我目前为止的剧本:

^{pr2}$

我可以用其他元素替换重复的元素,然后将soup对象转储到一个新的字符串中,然后将其发布到restapi中吗?在

注意:我使用html.parser,因为我can't get the xml parser to work但它可以正常工作,理解HTML比XML解析更自由。在


Tags: 文件name标记脚本模板idparser消息
1条回答
网友
1楼 · 发布于 2024-10-03 17:27:07

您可以使用^{}^{}方法:

for repElem in repElemList:
    print("Processing repElem...")
    repElemID = repElem.get('id')
    repElemName = repElem.get('name')

    repElem.replace_with(xmlSoup.new_tag("somenewtag"))

然后,可以使用str(soup)soup.prettify()转储“汤”。在

相关问题 更多 >