【问题标题】:Get commented nodes in XML获取 XML 中的注释节点
【发布时间】:2022-01-20 22:21:25
【问题描述】:

环境:Python 3.9.7、Windows 10

如何获取注释节点的 XPATH?


示例 XML (ex.xml)

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E">AUS</neighbor>
        <!-- A1 -->
        <neighbor name="Switzerland" direction="W">SWI</neighbor>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <!-- B1 -->
        <neighbor name="Malaysia" direction="N"/>
    </country>
</data>

我的期望

import xml.etree.ElementTree as et

def parse_commented_nodes(root):
    """
    Returns something like
    {
        "A1" : "./country[@name='Liechtenstein']/neighbor[@name='Austria']",
        "B1" : "./country[@nmae='Singapore']/gdppc"
    }
    """
    return {}

tree = et.parse("ex.xml")
root = tree.getroot()
res = parse_commented_nodes(root)

我的想法

  1. 以文本形式读取文件。
  2. 查找评论之前的行。
  3. 从节点到根迭代地获取父节点。

但我在上述方法中“获得父母”时遇到了问题。例如,

annotated_node = root.find(".//neighbor[@name='Austria']")
print(annotated_node.find("..")) # None
print(annotated_node.find("./..")) # None

我已经搜索了使用 Python 的默认 xml 模块获取节点的父节点(或获取完整 XPATH)的方法,但找不到有效的方法。


How to read commented text from XML file in python

我的问题与上述类似,但不是重复的。它找到“cmets”,但我需要“cmets 之前的节点”。

【问题讨论】:

  • OP 想要做的不仅仅是获取评论节点。
  • 使用 lxml,注释节点很容易找到(使用.xpath('//comment()')),前面的兄弟节点也是如此(使用.getprevious())。使用.getparent() 获取节点的父节点。用 ElementTree 做这些事情并非不可能,但肯定更具挑战性。
  • 为什么要知道 cmets 的 xpath?
  • @mzjn 这对我来说是完美的。非常感谢。

标签: python xml


【解决方案1】:

问题通过使用 lxml 作为@mzjn 建议解决。

from lxml import etree as et

def parse_commented_nodes(tree):
    res = {}
    for node in tree.iter():
        if "function Comment" in str(node.tag):
            res[node.text] = tree.getpath(node.getprevious())
    return res

tree = et.parse("ex.xml")
res = parse_commented_nodes(tree)

【讨论】:

    猜你喜欢
    • 2012-12-08
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2018-05-07
    • 1970-01-01
    • 2011-08-23
    相关资源
    最近更新 更多