繁体   English   中英

无法访问XML中的子元素

[英]Can't access child elements in XML

我试图将XML格式的字符串解析为一些普通的python对象,并且尝试使用findfindall方法访问某些子元素,但它不起作用。

这是我要解析的XML数据:

<?xml version="1.0" ?>
<ItemSearchResponse
    xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">

    <Items>
        <Request>
            <IsValid>True</IsValid>
            <ItemSearchRequest>
                <Keywords>iphone</Keywords>
                <ResponseGroup>ItemAttributes</ResponseGroup>
                <SearchIndex>All</SearchIndex>
            </ItemSearchRequest>
        </Request>
        <TotalResults>40721440</TotalResults>
        <TotalPages>4072144</TotalPages>

        <Item>
            <ASIN>B00YV50QU4</ASIN>
            <ParentASIN>B018GTHAKO</ParentASIN>
            <DetailPageURL>http://www.amazon.com/Apple-iPhone-MD439LL-Smartphone-Refurbished/dp/B00YV50QU4%3Fpsc%3D1%26SubscriptionId%3DAKIAIEEA4BKMTHTI2T7A%26tag%3Dshopit021-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB00YV50QU4</DetailPageURL>
            <ItemLinks>

            </ItemLinks>
            <ItemAttributes>
            </ItemAttributes>
        </Item>
        <Item>
            <ASIN>B00VHSXBUA</ASIN>
            <ParentASIN>B0152TROY8</ParentASIN>
            <ItemAttributes>
            </ItemAttributes>
        </Item>
    </Items>
</ItemSearchResponse>

为了使此样本更短,我删除了一些数据。

这是我的代码。

data  = et.fromstring(response)
            items = data[0][3]
            print items.tag
            items = data[0].findall('item')
            print len(items.findall('.//item'))

访问子节点('item')的第一种方法是使用列表索引符号,并且运行良好。 但是使用find all方法无法正常工作,并且len()始终返回0。

我尝试使用XPath和其他方式,但是使用索引是使其工作的唯一方法。

为什么像findfindall这样的方法不起作用?

为什么像find和findall这样的方法不起作用?

因为没有名为Item元素。 您的文档定义的默认XML命名空间http://webservices.amazon.com/AWSECommerceService/2011-08-01 ,这意味着,看起来像一个元素<Item>您的文档中实际上是包含在该命名空间,距离不同在没有默认XML名称空间(或具有其他XML名称空间)的文档中看起来像<Item>的元素。

您想要类似的东西:

>>> ns = 'http://webservices.amazon.com/AWSECommerceService/2011-08-01'
>>> items = data[0].findall('{%s}Item' % ns)
>>> items
[<Element {http://webservices.amazon.com/AWSECommerceService/2011-08-01}Item at 0x7f1cbaaba8c0>, <Element {http://webservices.amazon.com/AWSECommerceService/2011-08-01}Item at 0x7f1cbaaba680>]

或者,使用XPath:

>>> items = data[0].xpath('n:Item', namespaces={'n': ns})
>>> items
[<Element {http://webservices.amazon.com/AWSECommerceService/2011-08-01}Item at 0x7f1cbaaba8c0>, <Element {http://webservices.amazon.com/AWSECommerceService/2011-08-01}Item at 0x7f1cbaaba680>]

暂无
暂无

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

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