【问题标题】:Parsing xml with prefix解析带前缀的xml
【发布时间】:2013-01-30 22:13:02
【问题描述】:

如何使用 lxml 解析以下区域值?

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<mstns:NewDataSet xmlns:mstns="AscentMetadataReport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <mstns:Report>
        <mstns:Metadata>
            <mstns:Detail_Collection>
                <mstns:Detail>
                    <mstns:Territory>ARGENTINA</mstns:Territory>

这是我尝试过的:

node=etree.fromstring(contents)
territory = node.find('NewDataSet/Report/Metadata/Detail_collection/Detail/Territory')

虽然上述方法不起作用。我将如何解析这里的领土?

【问题讨论】:

  • 我对 Python 一无所知,但在 C# 中,必须使用 XmlNamespaceManager 才能解析带前缀的 XML。你可能需要在 Python 中做类似的事情。
  • 看到这个question 似乎与你的问题有关。
  • @UmarFarooqKhawaja:对于 cmets,您必须对链接使用 [text](url) 语法。
  • 是的,这是一个答案。 Stackoverflow 自动将我的答案转换为评论:/

标签: python xml lxml xml-namespaces


【解决方案1】:

在这里使用命名空间:

http://lxml.de/tutorial.html#namespaces

territory = node.find('mstns:ISOCountry',namespaces={'mstns':'AscentMetadataReport'}).text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2017-12-09
    相关资源
    最近更新 更多