从值标签Etree XML python中提取文本

时间:2018-02-28 09:01:12

标签: python xml python-3.x xml-parsing elementtree

我想从value标签中提取文本,我的xml代码片段和尝试如下所示:

<datas>
  <data>
    <column datatype='string' name='[Sub-Category (group)]' role='dimension' type='nominal'>
      <calculation class='categorical-bin' column='[Product Sub-Category]' new-bin='false'>
        <bin value='&quot;Envelopes&quot;'>
          <value>&quot;Envelopes&quot;</value>
          <value>&quot;Labels&quot;</value>
          <value>&quot;Pens &amp; Art Supplies&quot;</value>
          <value>&quot;Rubber Bands&quot;</value>
          <value>&quot;Scissors, Rulers and Trimmers&quot;</value>
        </bin>
      </calculation>
   </column>      
</data>
</datas>

我的尝试:

root = 'myxmlfile.xml'
valuelist = []
for i in root.findall('./datas/data/column/calculation/bin')
    val  = i.find('value')
    if val:
       for j in val:
           valuelist.append(j.text)
  • 我没有得到正确的结果。

3 个答案:

答案 0 :(得分:1)

这可能会有所帮助

# -*- coding: utf-8 -*-
s = """<datas>
  <data>
<column datatype='string' name='[Sub-Category (group)]' role='dimension' type='nominal'>
              <calculation class='categorical-bin' column='[Product Sub-Category]' new-bin='false'>
                <bin value='&quot;Envelopes&quot;'>
                  <value>&quot;Envelopes&quot;</value>
                  <value>&quot;Labels&quot;</value>
                  <value>&quot;Pens &amp; Art Supplies&quot;</value>
                  <value>&quot;Rubber Bands&quot;</value>
                  <value>&quot;Scissors, Rulers and Trimmers&quot;</value>
                </bin>
              </calculation>
    </column>
 </data>
</datas>"""

import xml.etree.ElementTree as et
tree = et.fromstring(s)
for i in tree.findall('.//data/column/calculation/bin'):
    for j in i.findall('value'):
        print(j.text)

<强>输出

"Envelopes"
"Labels"
"Pens & Art Supplies"
"Rubber Bands"
"Scissors, Rulers and Trimmers"

答案 1 :(得分:1)

试试这个:

root = open('/your/path_to_file/data.xml', 'rb+')
doc =  ET.parse(root).getroot()
valuelist = []
for i in doc.findall('.//bin'):
    val  = i.findall('value')
    for v in val:
        valuelist.append(v.text)
print valuelist

输出:

['"Envelopes"', '"Labels"', '"Pens & Art Supplies"', '"Rubber Bands"', '"Scissors, Rulers and Trimmers"']
[Finished in 0.0s]

答案 2 :(得分:1)

Rakesh的答案很棒,只是想我会为你的代码无效的原因添加一些解释。

首先,您需要将XML转换为ElementTree - 这基本上只是一个Python对象,其元素和子元素的树状结构与您的XML相对应,但您可以在Python中使用它。

如果您的XML位于文件中(而不仅仅是代码中的字符串),您可以执行以下操作:

tree = ET.parse('myxmlfile.xml')

然后root是&#34;最外面的&#34;这棵树的元素,你需要掌握它,以便能够在树上工作并找到元素等:

root = tree.getroot()

(如果您执行ET.fromstring(s),则会返回根元素,因此您不需要进行getroot步骤。)

在您的示例中,rootdatas元素,这是您的一个问题:您的路径不需要包含数据&#39;就像你已经从那里开始的那样。

val = i.find('value')只会返回第一个value元素,而不是您想要的所有value元素的列表。因此,当您尝试for j in val时,Python实际上是在尝试查找value元素的子元素(它不存在),因此它没有任何附加到{{{1}的元素。 1}}。您需要在此处使用valuelist,如果将其与findall()循环结合使用,那么您就不需要for检查if val如果for变空,那么循环就不会运行。

把所有这些放在一起:

findall()
然后

import xml.etree.ElementTree as ET tree = ET.parse('myxmlfile.xml') # change to wherever your file is located root = tree.getroot() binlist = [] for i in root.findall('./data/column/calculation/bin'): valuelist = [] for j in i.findall('value'): valuelist.append(j.text) binlist.append(valuelist) 是一个列表,列表中的每个项目都是该bin的值列表。

如果您只有一个bin,那么您可以简化代码的后半部分:

binlist

请注意,我已使用import xml.etree.ElementTree as ET tree = ET.parse('myxmlfile.xml') # change to wherever your file is located root = tree.getroot() bin = root.find('./data/column/calculation/bin') valuelist = [] for j in bin.findall('value'): valuelist.append(j.text) 而非ET导入et(这似乎是惯例)。这也假设ElementTree是XML的第一个元素。如果您提供的代码段嵌套在一个更大的XML文件中,那么您首先需要通过执行以下操作来获取该元素:

datas

这些参考资料可能对您有所帮助:

相关问题