我需要更新一个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但是它只添加列表的第一个单词,第一个值标记。
事先非常感谢
发布于 2021-01-16 01:16:27
有几种方法来处理这个问题,但是尝试一下这个方法,看看它是否有效。
将for循环更改为:
for word in words:
ntag = soup.new_tag('value')
ntag.string = word
mynewtag.insert(1,ntag)https://stackoverflow.com/questions/65743801
复制相似问题