首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用python将整个xml元素、属性和数据复制到具有特定id的新xml文件中

如何使用python将整个xml元素、属性和数据复制到具有特定id的新xml文件中
EN

Stack Overflow用户
提问于 2021-07-30 06:50:09
回答 1查看 66关注 0票数 1

下面的是我的示例xml源文件

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.sample.com/xml/catalog" catalog-id="sample-catalog">
<product product-id="214146430">
<online-flag>false</online-flag>
<online-flag site-id="sample_ae">false</online-flag>
<available-flag>true</available-flag>
<searchable-flag>true</searchable-flag>
<tax-class-id>standard</tax-class-id>
<page-attributes/>
<custom-attributes>
<custom-attribute attribute-id="adultsize">L</custom-attribute>
</custom-attributes>
</product>
<product product-id="214146123">
<online-flag>false</online-flag>
<online-flag site-id="sample_ae">false</online-flag>
<available-flag>true</available-flag>
<searchable-flag>true</searchable-flag>
<tax-class-id>standard</tax-class-id>
<page-attributes/>
<custom-attributes>
<custom-attribute attribute-id="adultsize">L</custom-attribute>
</custom-attributes>
</product>
</catalog>

我只想将产品id 214146430复制到New文件,它应该如下所示

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.sample.com/xml/catalog" catalog-id="sample-catalog">
<product product-id="214146430">
<online-flag>false</online-flag>
<online-flag site-id="sample_ae">false</online-flag>
<available-flag>true</available-flag>
<searchable-flag>true</searchable-flag>
<tax-class-id>standard</tax-class-id>
<page-attributes/>
<custom-attributes>
<custom-attribute attribute-id="adultsize">L</custom-attribute>
</custom-attributes>
</product>
</catalog>

我目前使用的是xml.etree.ElementTree和xml.dom,但没有运气,但它只是复制整个xml,这不是预期的。

下面是我的python代码

代码语言:javascript
运行
复制
import xml.etree.ElementTree as ET

tree = ET.parse('Development/product_data_parser/emporio-imoprt-test.xml')
root = tree.getroot()

print(ET.tostring(root, encoding='utf8').decode('utf8'))

非常感谢您的帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-31 10:50:56

您可以这样做,尽管此解决方案可能特定于您的用例:-

代码语言:javascript
运行
复制
import xml.etree.ElementTree as ET
import re

# A list of product IDs that you want to keep
keep = ['214146430']

# Figure out the namespace (used in tag matching later)
def getnamespace(root):
    m = re.match(r'\{.*\}', root.tag)
    return m.group(0) if m is not None else ''

tree = ET.parse('Development/product_data_parser/emporio-imoprt-test.xml')
root = tree.getroot()
namespace = getnamespace(root)
for elem in root.findall(f'{namespace}product'):
    if elem.attrib['product-id'] not in keep:
        root.remove(elem)
print(ET.tostring(root, encoding='utf8').decode('utf8'))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68586581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档