我有以下 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
查询来搜索文档中的任何元素:
- 只获取第一个元素:
from lxml import etree
doc = etree.parse('file.xml')
memoryElem = doc.find('.//BodyNum')
memoryElem.text
# 6168
- 获取所有元素:
[ b.text for b in doc.iterfind('.//BodyNum') ]
# ['6168', '6169']
关于python - python从xml文件中读取数据的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59157419/