Python lxml - 使用xml:lang属性检索元素

时间:2015-07-06 16:10:13

标签: python xml lxml

我有一些xml,它有多个具有相同名称的元素,但每个元素都使用不同的语言,例如:

<Title xml:lang="FR" type="main">Les Tudors</Title>
<Title xml:lang="DE" type="main">Die Tudors</Title>
<Title xml:lang="IT" type="main">The Tudors</Title>

通常,我会使用其属性检索元素,如下所示:

titlex = info.find('.//xmlns:Title[@someattribute=attributevalue]', namespaces=nsmap)

如果我尝试用[@xml:lang =“FR”](例如)执行此操作,则会收到回溯错误:

  File "D:/Python code/RBM CRID, Title, Genre/CRID, Title, Genre, Age rating, Episode Number, Descriptions V1.py", line 29, in <module>
    titlex = info.find('.//xmlns:Title[@xml:lang=PL]', namespaces=nsmap) 

  File "lxml.etree.pyx", line 1457, in lxml.etree._Element.find (src\lxml\lxml.etree.c:51435)

  File "C:\Python34\lib\site-packages\lxml\_elementpath.py", line 282, in find
    it = iterfind(elem, path, namespaces)

  File "C:\Python34\lib\site-packages\lxml\_elementpath.py", line 272, in iterfind
    selector = _build_path_iterator(path, namespaces)

  File "C:\Python34\lib\site-packages\lxml\_elementpath.py", line 256, in _build_path_iterator
    selector.append(ops[token[0]](_next, token))

  File "C:\Python34\lib\site-packages\lxml\_elementpath.py", line 134, in prepare_predicate
    token = next()

  File "C:\Python34\lib\site-packages\lxml\_elementpath.py", line 80, in xpath_tokenizer
    raise SyntaxError("prefix %r not found in prefix map" % prefix) SyntaxError: prefix 'xml' not found in prefix map

我对此并不感到惊讶,但我想了解如何解决这个问题。

谢谢!

根据要求,提供一个简洁但完整的代码集(如果删除[bitsinsquarebrackets],它会按预期工作):

import lxml
import codecs

file_name = (input('Enter the file name, excluding .xml extension: ') + '.xml')# User inputs file name
print('Parsing ' + file_name)


#----- Sets up import and namespace

from lxml import etree

parser = lxml.etree.XMLParser()


tree = lxml.etree.parse(file_name, parser)                                 # Name of file to test goes here
root = tree.getroot()

nsmap = {'xmlns': 'urn:tva:metadata:2012',
         'mpeg7': 'urn:tva:mpeg7:2008'}

#----- This code writes the output to a file

with codecs.open(file_name+'.log', mode='w', encoding='utf-8') as f:                        # Name the output file
    f.write(u'CRID|Title|Genre|Rating|Short Synopsis|Medium Synopsis|Long Synopsis\n')
    for info in root.xpath('//xmlns:ProgramInformation', namespaces=nsmap):
       titlex = info.find('.//xmlns:Title[xml:lang="PL"]', namespaces=nsmap)             # Retreve the title
       title = titlex.text if titlex != None else 'Missing'             # If there isn't a title, print an alternative word
       f.write(u'{}\n'.format(title))                     # Write all the retrieved values to the same line with bar seperators and a new line

2 个答案:

答案 0 :(得分:1)

xml中的xml:lang前缀不需要在XML文档中声明,但如果要在XPath查找中使用xml:lang,则必须在中定义前缀映射Python代码。

保留xml前缀(与#34;普通&#34;名称空间前缀相对应)并定义为绑定到http://www.w3.org/XML/1998/namespace。请参阅Namespaces in XML 1.0 W3C建议。

示例:

from lxml import etree

# Required mapping
nsmap = {"xml": "http://www.w3.org/XML/1998/namespace"}

XML = """
<root>
  <Title xml:lang="FR" type="main">Les Tudors</Title>
  <Title xml:lang="DE" type="main">Die Tudors</Title>
  <Title xml:lang="IT" type="main">The Tudors</Title>
</root>"""

doc = etree.fromstring(XML)

title_FR = doc.find('Title[@xml:lang="FR"]', namespaces=nsmap)
print title_FR.text

输出:

Les Tudors

如果xml前缀没有映射,则会获得&#34; 前缀&#39; xml&#39;在前缀地图中找不到&#34;错误。如果映射到xml前缀的URI不是http://www.w3.org/XML/1998/namespace,则上面代码段中的find方法不会返回任何内容。

答案 1 :(得分:0)

如果您可以控制xml文件,则应将xml:lang属性更改为lang

或者,如果您没有该控件,我建议您在nsmap中添加xml,例如 -

nsmap = {'xmlns': 'urn:tva:metadata:2012',
         'mpeg7': 'urn:tva:mpeg7:2008',
         'xml': '<namespace>'}