【发布时间】:2021-01-15 21:31:13
【问题描述】:
我需要更新一个 XML 文件。它的结构是
<product sku="xyz">
...
<custom-attributes>
<custom-attribute name="attrib1">test</custom-attribute>
...
</custom-attributes>
</product>
我想添加一条具有多值自定义属性的行,因此所需的结构如下所示:
<custom-attributes>
<custom-attribute name="attrib1">test</custom-attribute>
...
<custom-attribute name="new1">
<value>word1</value>
<value>word2</value>
....
</custom-attribute>
</custom-attributes>
我写了下面的python代码
precision = {"name" : "new1"}
for sku in soup.find_all('product'):
tagCustoms = sku.find('custom-attributes')
mynewtag = soup.new_tag('custom-attribute', attrs = precision)
tagCustoms.append(mynewtag)
for word in words: # words is a list
mynewtag.insert(1,soup.new_tag('value'))
它可以工作......除了我找不到如何定义值标签中的内容......如何在同一个循环中从单词列表中分配每个单词?
我被这个结果卡住了
<custom-attribute name="new1">
<value></value>
<value></value>
....
</custom-attribute>
</custom-attributes>
我试过这段代码
for sku in soup.find_all('product'):
tagCustoms = sku.find('custom-attributes')
mynewtag = soup.new_tag('custom-attribute', attrs = precision)
tagCustoms.append(mynewtag)
for word in words: # words is a list
mynewtag.insert(1,soup.new_tag('value'))
mynewtag.value.string = word
但它只将列表的第一个单词添加到第一个值标签。
在此先感谢
【问题讨论】:
标签: python-3.x xml beautifulsoup