繁体   English   中英

在标签上解析带有前缀的.xml? xml.etree.ElementTree

[英]parse .xml with prefix's on tags? xml.etree.ElementTree

我可以读取标签,除非有前缀。 我没有运气搜索SO以前的问题。

我需要阅读media:content 我试过image = node.find("media:content") Rss输入:

<channel>
  <title>Popular  Photography in the last 1 week</title>
  <item>
    <title>foo</title>
    <media:category label="Miscellaneous">photography/misc</media:category>
    <media:content url="http://foo.com/1.jpg" height="375" width="500" medium="image"/>
  </item>
  <item> ... </item>
</channel>

我可以读一个兄弟标签title

from xml.etree import ElementTree
with open('cache1.rss', 'rt') as f:
    tree = ElementTree.parse(f)

for node in tree.findall('.//channel/item'):
    title =  node.find("title").text 

我一直在使用文档,但仍然坚持'前缀'部分。

以下是使用ElementTree的 XML命名空间的示例:

>>> x = '''\
<channel xmlns:media="http://www.w3.org/TR/html4/">
  <title>Popular  Photography in the last 1 week</title>
  <item>
    <title>foo</title>
    <media:category label="Miscellaneous">photography/misc</media:category>
    <media:content url="http://foo.com/1.jpg" height="375" width="500" medium="image"/>
  </item>
  <item> ... </item>
</channel>
'''
>>> node = ElementTree.fromstring(x)
>>> for elem in node.findall('item/{http://www.w3.org/TR/html4/}category'):
        print elem.text


photography/misc

media是一个XML命名空间,必须先用xmlns:media="..."定义它。 有关如何在lxml中定义用于XPath表达式的xml命名空间,请参阅http://lxml.de/xpathxslt.html#namespaces-and-prefixes

暂无
暂无

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

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