【问题标题】:Getting rows from XML using XPath and Python使用 XPath 和 Python 从 XML 获取行
【发布时间】:2009-07-20 19:50:51
【问题描述】:

我想使用以下方法从 XML 中获取一些行(z:row 行):

<rs:data>
    <z:row Attribute1="1" Attribute2="1" />
    <z:row Attribute1="2" Attribute2="2" />
    <z:row Attribute1="3" Attribute2="3" />
    <z:row Attribute1="4" Attribute2="4" />
    <z:row Attribute1="5" Attribute2="5" />
    <z:row Attribute1="6" Attribute2="6" />
</rs:data>

我在使用 (Python) 时遇到问题:

ElementTree.parse('myxmlfile.xml').getroot().findall('//z:row')

我认为在这种情况下有两点是无效的。

有人知道我该怎么做吗?

【问题讨论】:

  • XPathGet 是一个函数吗?来自什么编程环境?
  • 将 XPathGet 视为返回所有节点的函数。

标签: python xml xpath


【解决方案1】:

如果我这样定义命名空间:

<?xml version="1.0"?>
<rs:data xmlns="http://example.com" xmlns:rs="http://example.com/rs" xmlns:z="http://example.com/z">
  <z:row Attribute1="1" Attribute2="1" />
  <z:row Attribute1="2" Attribute2="2" />
  <z:row Attribute1="3" Attribute2="3" />
  <z:row Attribute1="4" Attribute2="4" />
  <z:row Attribute1="5" Attribute2="5" />
  <z:row Attribute1="6" Attribute2="6" />
</rs:data>

Python ElementTree-API 可以这样使用:

ElementTree.parse("r.xml").getroot().findall('{http://example.com/z}row')
# => [<Element {http://example.com/z}row at 551ee0>, <Element {http://example.com/z}row at 551c60>, <Element {http://example.com/z}row at 551f08>, <Element {http://example.com/z}row at 551be8>, <Element {http://example.com/z}row at 551eb8>, <Element {http://example.com/z}row at 551f30>]

另见http://effbot.org/zone/element.htm#xml-namespaces

【讨论】:

【解决方案2】:

如果您不想正确设置命名空间,可以像这样忽略它们:

XPathGet("//*[local-name() = 'row']")

选择名称(无命名空间)为row的每个节点。

【讨论】:

    【解决方案3】:

    “z:”前缀表示 XML 命名空间。您需要找出该命名空间是什么,然后执行以下操作:

    XmlDocument doc = new XmlDocument();
    doc.Load(@"File.xml");
    XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
    ns.AddNamespace("z", @"http://thenamespace.com");
    XmlNodeList nodes = doc.SelectNodes(@"//z:row", ns);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2018-05-25
      • 1970-01-01
      • 2016-03-14
      相关资源
      最近更新 更多