简体   繁体   English

xmlns命名空间破坏lxml

[英]xmlns namespace breaking lxml

I am trying to open an xml file, and get values from certain tags. 我试图打开一个xml文件,并从某些标签获取值。 I have done this a lot but this particular xml is giving me some issues. 我做了很多,但这个特殊的xml给了我一些问题。 Here is a section of the xml file: 这是xml文件的一部分:

<?xml version='1.0' encoding='UTF-8'?>
<package xmlns="http://apple.com/itunes/importer" version="film4.7">
  <provider>filmgroup</provider>
  <language>en-GB</language>
  <actor name="John Smith" display="Doe John"</actor>
</package>

And here is a sample of my python code: 这是我的python代码示例:

metadata = '/Users/mylaptop/Desktop/Python/metadata.xml'
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
open(metadata)
tree = etree.parse(metadata, parser)
root = tree.getroot()
for element in root.iter(tag='provider'):
    providerValue = tree.find('//provider')
    providerValue = providerValue.text
    print providerValue
tree.write('/Users/mylaptop/Desktop/Python/metadataDone.xml', pretty_print = True, xml_declaration = True, encoding = 'UTF-8')

When I run this it can't find the provider tag or its value. 当我运行它时,它找不到提供者标签或其值。 If I remove xmlns="http://apple.com/itunes/importer" then all work as expected. 如果我删除xmlns="http://apple.com/itunes/importer"那么所有工作都按预期进行。 My question is how can I remove this namespace, as i'm not at all interested in this, so I can get the tag values I need using lxml? 我的问题是如何删除这个命名空间,因为我对此并不感兴趣,所以我可以使用lxml获取我需要的标记值?

The provider tag is in the http://apple.com/itunes/importer namespace, so you either need to use the fully qualified name provider标记位于http://apple.com/itunes/importer命名空间中,因此您需要使用完全限定名称

{http://apple.com/itunes/importer}provider

or use one of the lxml methods that has the namespaces parameter , such as root.xpath . 或者使用具有namespaces参数的lxml方法之一,例如root.xpath Then you can specify it with a namespace prefix (eg ns:provider ): 然后,您可以使用名称空间前缀(例如ns:provider )指定它:

from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(metadata, parser)
root = tree.getroot()
namespaces = {'ns':'http://apple.com/itunes/importer'}
items = iter(root.xpath('//ns:provider/text()|//ns:actor/@name',
                       namespaces=namespaces))
for provider, actor in zip(*[items]*2):
    print(provider, actor)

yields 产量

('filmgroup', 'John Smith')

Note that the XPath used above assumes that <provider> and <actor> elements always appear in alternation. 请注意,上面使用的XPath假定<provider><actor>元素总是以交替显示。 If that is not true, then there are of course ways to handle it, but the code becomes a bit more verbose: 如果不是这样,那么当然有办法处理它,但代码变得更加冗长:

for package in root.xpath('//ns:package', namespaces=namespaces):
    for provider in package.xpath('ns:provider', namespaces=namespaces):
        providerValue = provider.text
        print providerValue
    for actor in package.xpath('ns:actor', namespaces=namespaces):
        print actor.attrib['name']

My suggestion is to not ignore the namespace but, instead, to take it into account. 我的建议是不要忽略命名空间,而是要考虑它。 I wrote some related functions (copied with slight modification) for my work on the django-quickbooks library. 我为django-quickbooks库上的工作编写了一些相关的函数(经过轻微修改后复制)。 With these functions, you should be able to do this: 使用这些功能,您应该能够这样做:

providers = getels(root, 'provider', ns='http://apple.com/itunes/importer')

Here are those functions: 以下是这些功能:

def get_tag_with_ns(tag_name, ns):
    return '{%s}%s' % (ns, tag_name)

def getel(elt, tag_name, ns=None):
    """ Gets the first tag that matches the specified tag_name taking into
    account the QB namespace.

    :param ns: The namespace to use if not using the default one for
    django-quickbooks.
    :type  ns: string
    """

    res = elt.find(get_tag_with_ns(tag_name, ns=ns))
    if res is None:
        raise TagNotFound('Could not find tag by name "%s"' % tag_name)
    return res

def getels(elt, *path, **kwargs):
    """ Gets the first set of elements found at the specified path.

    Example:
        >>> xml = (
        "<root>" +
            "<item>" +
                "<id>1</id>" +
            "</item>" +
            "<item>" +
                "<id>2</id>"* +
            "</item>" +
        "</root>")
        >>> el = etree.fromstring(xml)
        >>> getels(el, 'root', 'item', ns='correct/namespace')
        [<Element item>, <Element item>]
    """

    ns = kwargs['ns']

    i=-1
    for i in range(len(path)-1):
        elt = getel(elt, path[i], ns=ns)
    tag_name = path[i+1]
    return elt.findall(get_tag_with_ns(tag_name, ns=ns))

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

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