繁体   English   中英

使用 Python ElementTree 提取特定的 XML 行

[英]Extracting Specific Lines of XML with Python ElementTree

我对我正在做的使用 Python 的项目有点卡住了——我对这个项目很陌生。 有人告诉我使用 ElementTree 并从传入的 XML 文件中获取指定的数据。 这听起来很简单,但我不擅长编程。 下面是一个(非常!)传入文件的小示例以及我尝试使用的代码。

我想要任何提示或下一步要去的地方。 我尝试搜索并遵循其他人所做的操作,但似乎无法获得相同的结果。 我的目标是获取包含在“活动”、“房间”和“方向”中的信息,但稍后我将需要获取更多信息。

我曾尝试使用 XPath,但效果不佳,尤其是在 xml 使用的命名空间以及我需要的所有内容的 XPath 会变得太大的情况下。 我已经简化了这个例子,所以我可以理解要做的原则,因为在此之后必须扩展它以从“AssetEquipment”和它们的多个实例中获取更多信息。 然后最终目标是将来自一个设备的所有信息保存到字典中,以便我以后可以操作它,每个新设备都在自己单独的字典中。

示例 XML:

<AssetData>
<Equipment>
    <AssetEquipment ID="3" name="PC960">
        <Active>Yes</Active>
        <Location>
            <RoomLocation>
                <Room>23</Room>
                <Area>
                    <X-Area>-1</X-Area>
                    <Y-Area>2.4</Y-Area>
                </Area>
            </RoomLocation>
        </Location>
        <Direction>Positive</Direction>
        <AssetSupport>12</AssetSupport>
    </AssetEquipment>
</Equipment>

示例代码:

tree = ET.parse('C:\Temp\Example.xml')
root = tree.getroot()

ns = "{http://namespace.co.uk}"

for equipment in root.findall(ns + "Equipment//"):
    tagname = re.sub(r'\{.*?\}','',equipment.tag)
    name = equipment.get('name')

    if tagname == 'AssetEquipment':
        print "\tName: " + repr(name)
        for attributes in root.findall(ns + "Equipment/" + ns + "AssetEquipment//"):
            attname = re.sub(r'\{.*?\}','',attributes.tag)
            if tagname == 'Room': #This does not work but I need it to be found while
                                  #in this instance of "AssetEquipment" so it does not
                                  #call information from another asset instead.
                room = equipment.text
                print "\t\tRoom:", repr(room)
import xml.etree.cElementTree as ET
tree = ET.parse('test.xml')
for elem in tree.getiterator():
    if elem.tag=='{http://www.namespace.co.uk}AssetEquipment':
        output={}
        for elem1 in list(elem):
            if elem1.tag=='{http://www.namespace.co.uk}Active':
                output['Active']=elem1.text
            if elem1.tag=='{http://www.namespace.co.uk}Direction':
                output['Direction']=elem1.text
            if elem1.tag=='{http://www.namespace.co.uk}Location':
                for elem2 in list(elem1):
                    if elem2.tag=='{http://www.namespace.co.uk}RoomLocation':
                        for elem3 in list(elem2):
                            if elem3.tag=='{http://www.namespace.co.uk}Room':
                                output['Room']=elem3.text
        print output

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM