python 解析 XML 解析包含“xml”的属性以名义
我不明白以下行为。 我通过将字符串传递到 XML eetree 来解析 XML 字符串,如下所示:
from lxml import etree
mini_example = '''
<body>
<div facs="pre-publication" type="description" xml:base="/api/emi" xml:id="f877d62ae6e2c8ab4011c81c474217e0" xml:lang="en">
<title desc="invention-title">Low tech high output PV</title>
<head xml:id="_45a0fe0003">FIELD </head>
<p n="0001" xml:id="_45a0fe0004">The present doc is about fooball</p>
<head xml:id="_45a0fe0005">BACKGROUND</head>
<p n="0002" xml:id="_45a0fe0006">Once upon a time</p>
</div>
</body>'''
parser = etree.XMLParser(resolve_entities=False, strip_cdata=False, recover=True, ns_clean=True)
XML_tree = etree.fromstring(mini_example.encode() , parser=parser)
paragraphs = './/p[@xml:id]'
heads = './/head[@xml:id]'
titles = './/title'
xml_query = '|'.join([paragraphs, heads, titles])
all_elements = XML_tree.xpath(xml_query)
解析元素的属性时,我得到:
for para in all_elements:
print(para.attrib)
其结果是:
{'desc': 'invention-title'}
{'{http://www.w3.org/XML/1998/namespace}id': '_45a0fe0003'}
{'n': '0001', '{http://www.w3.org/XML/1998/namespace}id': '_45a0fe0004'}
{'{http://www.w3.org/XML/1998/namespace}id': '_45a0fe0005'}
{'n': '0002', '{http://www.w3.org/XML/1998/namespace}id': '_45a0fe0006'}
因此属性名称“XML:”被转换为“{http://www.w3.xml”。 org/XML/1998/namespace}”。 为什么会发生这种情况?
当然,我该怎么办?因为我有多个 xml:id、xml:base 等属性名称。
I dont understand the following behaiviour.
I am parsing XML string by passing a string into XML eetree as follows:
from lxml import etree
mini_example = '''
<body>
<div facs="pre-publication" type="description" xml:base="/api/emi" xml:id="f877d62ae6e2c8ab4011c81c474217e0" xml:lang="en">
<title desc="invention-title">Low tech high output PV</title>
<head xml:id="_45a0fe0003">FIELD </head>
<p n="0001" xml:id="_45a0fe0004">The present doc is about fooball</p>
<head xml:id="_45a0fe0005">BACKGROUND</head>
<p n="0002" xml:id="_45a0fe0006">Once upon a time</p>
</div>
</body>'''
parser = etree.XMLParser(resolve_entities=False, strip_cdata=False, recover=True, ns_clean=True)
XML_tree = etree.fromstring(mini_example.encode() , parser=parser)
paragraphs = './/p[@xml:id]'
heads = './/head[@xml:id]'
titles = './/title'
xml_query = '|'.join([paragraphs, heads, titles])
all_elements = XML_tree.xpath(xml_query)
When parsing the attributes of the elements I get:
for para in all_elements:
print(para.attrib)
which results in:
{'desc': 'invention-title'}
{'{http://www.w3.org/XML/1998/namespace}id': '_45a0fe0003'}
{'n': '0001', '{http://www.w3.org/XML/1998/namespace}id': '_45a0fe0004'}
{'{http://www.w3.org/XML/1998/namespace}id': '_45a0fe0005'}
{'n': '0002', '{http://www.w3.org/XML/1998/namespace}id': '_45a0fe0006'}
So the attribute name "XML:" gets transformed into "{http://www.w3.org/XML/1998/namespace}".
Why is this happening?
and of course,what should I do? since I have multiple xml:id,xml:base, etc names of attributes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论