首页 > 解决方案 > 有没有办法将参数传递给xml?还是修改它?

问题描述

我想将某个参数传递给 xml,因此我不想通过创建它而成为具有所有值的原始 xml,而是想用一个参数(例如,用户输入)更改一个参数。

理想情况下,我一直在寻找类似的东西,<title> &param1 </title>并且以后能够传递我想要的任何参数,但我想这是不可能的。

因此,就像无法传递参数一样(或者至少从我搜索的内容来看),我考虑过在创建 xml 后对其进行编辑。

我主要使用 beautifulsoup 进行搜索,因为它是我想要使用的(以及我正在使用的)。这只是我项目的一小部分。例如thisthis是我的一些研究)。

所以这就是我想要做的功能:我们有一个 xml,我们找到我们想要编辑的部分,然后我们编辑它(我知道要访问它,它需要是一个整数pruebaEdit[anyString]是不正确的。

def editXMLTest():
    editTest="""<?xml version="1.0" ?>
<books>
  <book>
    <title>moon</title>
    <author>louis</author>
    <price>8.50</price>
  </book>
</books>
    """
    soup =BeautifulSoup(editTest)
    for tag in soup.find_all('title'):
        print (tag.string, '\n')
        #tag.string='invented title'
        editTest[tag]='invented title' #I know it has to be an integer, not a string
    print()
    print(editTest)

我的预期输出应该在 xml:<title>invented title</title>而不是<title>moon</title>.

编辑:将此添加到我的研究中

标签: pythonxmlbeautifulsoup

解决方案


您必须打印结果或soup不是原始字符串editTest

for tag in soup.find_all('title'):
    print (tag.string, '\n')
    tag.string='invented title'
print(soup)

推荐阅读