Python: 如何将XML元素作为参数传递

2024-04-19 22:36:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个XML文件,它看起来像:

<root>
  <product>
  ...multiple tags
  </product>
  <product>
  ...multiple tags
  </product>
  .
  .
  .
</root>

文件中有多个产品,每个产品都有一组标记。我想传递与产品相对应的XML作为HTTP请求的参数。我浏览了this,但找不到如何“获取”子元素。在

有人能帮忙吗。谢谢

编辑:我尝试过使用:

^{pr2}$

但我得到了以下输出,而不是每个子级对应的XML:

<Element 'product' at 0xb729328c>
<Element 'product' at 0xb7293d0c>
<Element 'product' at 0xb72987ec>
<Element 'product' at 0xb729b2cc>
<Element 'product' at 0xb729bcec>

Tags: 文件标记http元素编辑参数产品tags
2条回答

你通常会这样做:

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
root.findall('product')

结果来自根.findall将返回所有product项(作为数组),因此可以执行以下操作:

^{pr2}$

会检查所有的子项目

据我所知,您有一个XML文件,您需要提取每个<product />元素的数据,作为一个XML字符串,可以在HTTP请求中使用。通过扩展@nrathaus已经说过的话,我希望对你的问题给出一个稍微更完整的答案。在

我们可以得到^{}对象的列表,对应于<product />元素,如下所示:

from xml.etree import ElementTree

tree = ElementTree.parse('products.xml')
root = tree.getroot()
product_elements = root.findall('product')

然后使用^{}将这些元素转换为XML字符串。例如:

^{pr2}$

示例

产品.xml

<products>
  <product>
    <name>First product</name>
  </product>
  <product>
    <name>Second product</name>
  </product>
  <product>
    <name>Third product</name>
  </product>
</products>

测试.py

from xml.etree import ElementTree

tree = ElementTree.parse('products.xml')
root = tree.getroot()
product_elements = root.findall('product')

for product_element in product_elements:
    print(ElementTree.tostring(product_element))

输出

/tmp/xml$ python  version
Python 2.7.3
/tmp/xml$ python test.py 
<product>
    <name>First product</name>
  </product>

<product>
    <name>Second product</name>
  </product>

<product>
    <name>Third product</name>
  </product>

相关问题 更多 >