在python中解析嵌套xml

2024-09-30 03:25:43 发布

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

我有这个XML文件:

<?xml version="1.0" ?><XMLSchemaPalletLoadTechData xmlns="http://tempuri.org/XMLSchemaPalletLoadTechData.xsd">
  <TechDataParams>
    <RunNumber>sample</RunNumber>
    <Holder>sample</Holder>
    <ProcessToolName>sample</ProcessToolName>
    <RecipeName>sample</RecipeName>
    <PalletName>sample</PalletName>
    <PalletPosition>sample</PalletPosition>
    <IsControl>sample</IsControl>
    <LoadPosition>sample</LoadPosition>
    <HolderJob>sample</HolderJob>
    <IsSPC>sample</IsSPC>
    <MeasurementType>sample</MeasurementType>
  </TechDataParams>
  <TechDataParams>
    <RunNumber>sample</RunNumber>
    <Holder>sample</Holder>
    <ProcessToolName>sample</ProcessToolName>
    <RecipeName>sample</RecipeName>
    <PalletName>sample</PalletName>
    <PalletPosition>sample</PalletPosition>
    <IsControl>sample</IsControl>
    <LoadPosition>sample</LoadPosition>
    <HolderJob>sample</HolderJob>
    <IsSPC>sample</IsSPC>
    <MeasurementType>XRF</MeasurementType>
  </TechDataParams>
</XMLSchemaPalletLoadTechData>

这是我解析xml的代码:

^{pr2}$

但是当我打印每个节点时,我只得到一组“TechDataParams”,但我希望能够从XML中获取所有“TechDataParams”。在

如果我的问题有点不清楚,请告诉我。在


Tags: samplexmlholderrecipenameisspcpalletnameloadpositionholderjob
3条回答

请不要使用minidom解析XML,除非您希望自己拔出头发。在

我在这里用^{} module。一行,您就有一个包含所有所需数据的dict列表:

import xmltodict

data = """your xml here"""

data = xmltodict.parse(data)['XMLSchemaPalletLoadTechData']['TechDataParams']
for params in data:
    print dict(params)

印刷品:

^{pr2}$

这里有一个例子给你。将file_path替换为您自己的。在

我将RunNumber的值替换为001和{}。在

# -*- coding: utf-8 -*-
#!/usr/bin/python

from xml.dom import minidom

file_path = 'C:\\temp\\test.xml'

doc = minidom.parse(file_path)
TechDataParams = doc.getElementsByTagName('TechDataParams')
for t in TechDataParams:
    num = t.getElementsByTagName('RunNumber')[0]
    print 'num is ', num.firstChild.data

输出:

^{pr2}$

也是通过lxml.etree模块。在

  1. 输入包含名称空间,即http://tempuri.org/XMLSchemaPalletLoadTechData.xsd
  2. 使用xpath方法查找目标TechDataParams标记。在
  3. 获取TechDataParams标记的子项并创建字典,其中key是{},而{}是{}。在
  4. 追加到列表变量TechDataParams。在

代码:

from lxml import etree
root = etree.fromstring(content)
TechDataParams_info = []
for  i in root.xpath("//a:XMLSchemaPalletLoadTechData/a:TechDataParams", namespaces={"a": 'http://tempuri.org/XMLSchemaPalletLoadTechData.xsd'}):
    temp = dict()
    for j in i.getchildren():
        temp[j.tag.split("}", 1)[-1]] = j.text
    TechDataParams_info.append(temp)

print TechDataParams_info

输出:

^{pr2}$

相关问题 更多 >

    热门问题