lxml只获取前缀,然后返回元素名称

2024-04-19 23:02:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要lxml做两件事: 1) 列出xml文件中使用的各种前缀; 2) 指定前缀后,让lxml将所有元素名及其多个属性返回给我。你知道吗

对于此lxml:

<pref:MiscDetails contentRef='01-01_2016' misc='wha'>1000</pref:MiscDetails>
<pref:TestingThis contentRef='03-02_2017' misc='t' qual='5'>50</pref:TestingThis>
<pref:AnotherExample contentRef='01-01_2015' misc='x'>100000</pref:AnotherExample>
<test:AFinalExample contentRef='' te='t'>test</test:AFinalExample>

代码应该首先告诉我这个文件中的前缀是“pref”和“test”,然后我希望代码列出元素名及其与“pref”和“test”关联的属性。你知道吗

输出1:

"Listing prefixes:"
"pref"
"test"

输出2:

"Listing the prefix 'pref' element names and their attributes:"
"Element MiscDetails with attributes contentRef='01-01_2016' misc='wha'"
"Element TestingThis with attributes contentRef='03-02_2017' misc='t' qual='5'"
"Element AnotherExample with attributes contentRef='01-01_2015' misc='x'"

"Listing the prefix 'test' element names and their attributes:"
"Element AFinalExample with attributes contentRef='' te='t'"

谢谢!你知道吗


Tags: 文件test元素withelementlxmlattributesmisc
1条回答
网友
1楼 · 发布于 2024-04-19 23:02:05

文档或元素的nsmap属性将列出任何命名空间前缀:

>>> from lxml import etree
>>> doc = etree.fromstring("""<doc xmlns:pref='http://example.com'>
    <pref:MiscDetails>...</pref:MiscDetails></doc>""")
>>> doc.nsmap
{'pref': 'http://example.com'}

使用iter(){namespace-uri}*返回该名称空间中的所有元素(您必须在此处使用URI,它是名称空间中有意义的部分,而不是前缀,这对人类来说很方便):

>>> doc = etree.fromstring("<doc xmlns:pref='http://example.com'>
<pref:foo/><pref:bar/></doc>")
>>> [ el.tag for el in doc.iter('{http://example.com}*') ]
['{http://example.com}foo', '{http://example.com}bar']

lxml文档中的更多信息:http://lxml.de/tutorial.html#namespaces

相关问题 更多 >