"倒入所有的XPaths"

2024-04-28 02:30:17 发布

您现在位置:Python中文网/ 问答频道 /正文

lxml或exml是否有导出XML中所有xpath的函数?你知道吗

XML示例:

 <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>
         <content>Don't forget me this weekend!</content>
    </body>
    </note>

XPath结果:

\\note
\\note\to
\\note\from
\\note\heading
\\note\body
\\note\body\content

Tags: to函数from示例bodyxmlcontentlxml
1条回答
网友
1楼 · 发布于 2024-04-28 02:30:17

必须遍历树并在每个节点上调用getpath

x = """<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>
         <content>Don't forget me this weekend!</content>
    </body>
    </note>"""

from lxml import etree
from StringIO import StringIO
tree = etree.parse(StringIO(x))

paths = "\n".join(tree.getpath(n) for n in tree.iter())
print(paths)

输出:

/note
/note/to
/note/from
/note/heading
/note/body
/note/body/content

相关问题 更多 >