在python中如何从xml文件中读取数据

2024-09-29 23:29:03 发布

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

我有以下xml文件数据:

<?xml version="1.0" encoding="iso-8859-1" standalone="yes"?>
<rootnode>
  <TExportCarcass>
    <BodyNum>6168</BodyNum>
    <BodyWeight>331.40</BodyWeight>
    <UnitID>1</UnitID>
    <Plant>239</Plant>
    <pieces>
      <TExportCarcassPiece index="0">
        <Bruising>0</Bruising>
        <RFIDPlant></RFIDPlant>
      </TExportCarcassPiece>
      <TExportCarcassPiece index="1">
        <Bruising>0</Bruising>
        <RFIDPlant></RFIDPlant>
      </TExportCarcassPiece>
    </pieces>
  </TExportCarcass>
  <TExportCarcass>
    <BodyNum>6169</BodyNum>
    <BodyWeight>334.40</BodyWeight>
    <UnitID>1</UnitID>
    <Plant>278</Plant>
    <pieces>
      <TExportCarcassPiece index="0">
        <Bruising>0</Bruising>
        <RFIDPlant></RFIDPlant>
      </TExportCarcassPiece>
      <TExportCarcassPiece index="1">
        <Bruising>0</Bruising>
        <RFIDPlant></RFIDPlant>
      </TExportCarcassPiece>
    </pieces>
  </TExportCarcass>
</rootnode>

我使用python的lxml模块从xml文件读取数据,如下所示:

^{pr2}$

但它只打印None,而不是6168。请告诉我我做错了什么。在


Tags: 文件数据indexversionxmlplantpiecesunitid
3条回答

您需要迭代每个TExportCarcass标记,然后使用find访问{}

例如:

from lxml import etree

doc = etree.parse('file.xml')
for elem in doc.findall('TExportCarcass'):
    print(elem.find("BodyNum").text) 

输出:

^{pr2}$

或者

print([i.text for i in doc.findall('TExportCarcass/BodyNum')]) #-->['6168', '6169']

对文本字符串运行find时,它将只搜索根级别的元素。您可以在find中使用xpath查询来搜索文档中的任何元素:

  1. 仅获取第一个元素:
from lxml import etree
doc = etree.parse('file.xml')

memoryElem = doc.find('.//BodyNum')
memoryElem.text
# 6168
  1. 要获取所有元素:
^{pr2}$

1-使用/指定要提取的元素的树级别

2-使用.text提取元素的名称

doc = etree.parse('file.xml')
memoryElem = doc.find("*/BodyNum") #BodyNum is one level down
print(memoryElem.text)  #Specify you want to extract the name of the element

相关问题 更多 >

    热门问题