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

时间:2013-12-17 13:04:38

标签: python xml

我有一个XML文件,如下所示:

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

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

请有人帮忙。感谢

编辑:我尝试过使用:

import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()

for child in root:
    print child       //also tried child.text

但是我得到以下输出而不是与每个孩子对应的XML:

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

2 个答案:

答案 0 :(得分:1)

您通常会执行以下操作:

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

root.findall的结果将返回所有product项(作为数组),因此您可以这样做:

for product in root.findall('product'):

会检查所有子项目

答案 1 :(得分:0)

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

我们可以获得Element个对象的列表,对应于<product />个元素,如下所示:

from xml.etree import ElementTree

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

然后,使用ElementTree.tostring将每个元素转换为XML字符串。例如:

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

实施例

products.xml

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

test.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>
相关问题