【问题标题】:Get rect tag from this XML file从此 XML 文件中获取 rect 标记
【发布时间】:2015-06-05 14:28:05
【问题描述】:

如何在 Python 中使用 lxml 库从this XML 文件中获取?

我找不到合适的 XPATH 来获取标签。

【问题讨论】:

    标签: python xml svg xml-parsing lxml


    【解决方案1】:

    您需要处理namespaces(还有一个empty one):

    namespaces = {
      "dc":"http://purl.org/dc/elements/1.1/",
      "cc": "http://creativecommons.org/ns#",
      "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
      "svg": "http://www.w3.org/2000/svg",
      "myns": "http://www.w3.org/2000/svg"
    }
    
    tree = ET.fromstring(data)
    for rect in tree.xpath("//myns:rect", namespaces=namespaces):
        print rect.attrib.get("id")
    

    data 是您提供的 XML 字符串。

    出于测试目的,它只打印rect 元素id 属性:

    rect3347
    rect3349
    rect3351
    rect3351-1
    rect3351-17
    rect3351-1-4
    rect3397
    rect3399
    rect3401
    rect3403
    

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 2013-04-03
      • 2015-06-18
      相关资源
      最近更新 更多