簡體   English   中英

使用嵌套元素解析 XML 文件

[英]Parse XML File with nested Elements

我正在嘗試使用如下所示的嵌套元素導出和 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<GetCategoriesResponse xmlns="urn:ebay:apis:eBLBaseComponents">
    <Timestamp>2015-11-16T03:51:35.809Z</Timestamp>
    <Ack>Success</Ack>
    <Version>927</Version>
    <Build>E927_CORE_API_17590338_R1</Build>
    <CategoryArray>
            <Category>
            <BestOfferEnabled>true</BestOfferEnabled>
            <AutoPayEnabled>true</AutoPayEnabled>
            <CategoryID>20081</CategoryID>
            <CategoryLevel>1</CategoryLevel>
            <CategoryName>Antiques</CategoryName>
            <CategoryParentID>20081</CategoryParentID>
            </Category>
    </CategoryArray>
    <CategoryCount>18282</CategoryCount>
    <UpdateTime>2015-09-01T22:57:09.000Z</UpdateTime>
    <CategoryVersion>113</CategoryVersion>
    <ReservePriceAllowed>true</ReservePriceAllowed>
    <MinimumReservePrice>0.0</MinimumReservePrice>
</GetCategoriesResponse>

我正在嘗試訪問標簽的內容使用 python 元素樹我嘗試了不同的方法,例如:

import xml.etree.ElementTree as ET

xtree = ET.parse("categories.xml")
xroot = xtree.getroot()

for node in xroot.findall('CategoryArray'):
    for snode in node.findall('Category'):
            categoryName = snode.find("CategoryName").text
            categoryLevel = snode.find("CategoryLevel").text
            categoryParentID = snode.find('CategoryParentID').text
            
            print(categoryName, categoryLevel, categoryParentID)

但它沒有 output 什么,我做錯了什么?

Namespaces(ns) 是這里的關鍵,因此您需要考慮 ns. 有關更多文檔,請參閱。

import xml.etree.ElementTree as ET

xtree = ET.parse("categories.xml")
xroot = xtree.getroot()

ns = {'myns': 'urn:ebay:apis:eBLBaseComponents'} # define the namesapce

for node in xroot.findall('myns:CategoryArray',ns): # and then find them based on ns
    for snode in node.findall('myns:Category',ns):
            categoryName = snode.find("myns:CategoryName",ns).text
            categoryLevel = snode.find("myns:CategoryLevel",ns).text
            categoryParentID = snode.find('myns:CategoryParentID',ns).text
            
            print(categoryName, categoryLevel, categoryParentID)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM