【问题标题】:How to replace/remove XML tag with BeautifulSoup?如何用 BeautifulSoup 替换/删除 XML 标签?
【发布时间】:2017-03-31 05:27:22
【问题描述】:

我在本地文件中有 XML,它是最终消息的模板,该消息将 POSTed 发送到 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>

除了repeatingElement 标记需要替换为其他内容(脚本基于现有标记中的属性生成的 XML)之外,消息 XML 应该看起来相同。

到目前为止,这是我的脚本:

xmlData = None

with open('conf//test1.xml', 'r') as xmlFile:
    xmlData = xmlFile.read()

xmlSoup = BeautifulSoup(xmlData, 'html.parser')

repElemList = xmlSoup.find_all('repeatingelement')

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

    # now I do something with repElemID and repElemName
    # and no longer need it. I would like to replace it with <somenewtag/>
    # and dump what is in the soup object back into a string.
    # is it possible with BeautifulSoup?

我可以用其他东西替换重复元素,然后将汤对象转储到我可以发布到我的 REST API 的新字符串中吗?

注意:我使用的是html.parser,因为我使用的是can't get the xml parser to work,但它工作正常,理解HTML 比解析XML 更容易。

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:

    您可以使用.replace_with().new_tag() 方法:

    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() 倾倒“汤”。

    【讨论】:

    • 有趣,我只是同时想出了相同的解决方案
    • 不幸的是,在我的系统 (Win7) 上工作的唯一汤解析器是 html.parser(xml 不能按照 stackoverflow.com/questions/40640026/… 工作)将所有标签转换为小写,我的 REST API 区分大小写
    猜你喜欢
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    相关资源
    最近更新 更多