python - python从xml文件中读取数据的方法

标签 python xml lxml

我有以下 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 文件中读取数据,如下所示:

from lxml import etree

doc = etree.parse('file.xml')

memoryElem = doc.find('BodyNum')
print(memoryElem)        

但它只打印 None 而不是 6168。请建议我在这里做错了什么。

最佳答案

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

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

memoryElem = doc.find('.//BodyNum')
memoryElem.text
# 6168
  1. 获取所有元素:
[ b.text for b in doc.iterfind('.//BodyNum') ]
# ['6168', '6169']

关于python - python从xml文件中读取数据的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59157419/

相关文章:

python - 给定两个字符串列表,如何将它们转换为字典?

java - 通过pom.xml执行主类

python - 使用 Python 的维基百科

python - 解析源代码(Python)方法: Beautiful Soup, lxml、html5lib区别?

python lxml 添加一个保留所有父树的子元素

python - Xpath vs DOM vs BeautifulSoup vs lxml vs other 解析网页的最快方法是什么?

python - 使用脚本部分更新文档并添加缺少的字段

python - python中字典的效率 :

javascript - 为什么要区分单行注释和多行注释?

javascript - 使用 python 获取 javascript 表单内容