4

xml の新機能。Python ElementTree形式のxmlファイルを検索するXPathを探しています

<root>
<child>One</child>
<child>Two</child>
<child>Three</child>
</root>

"Two" で子を検索し、true/false を返す

それがのように始まった場合

from elementtree import ElementTree
root = ElementTree.parse(open(PathFile)).getroot()

どうすればこれを達成できますか

4

2 に答える 2

1

次の XPath 式が評価される場合:

    boolean(/*/*[.='Two'])

そのような要素 (文字列値が "Two" に等しい最上位要素の子) が存在する場合、結果はtrue です。

それ以外の場合はfalse

これが役に立ったことを願っています。

乾杯、

ディミトレ・ノヴァチェフ

于 2008-11-12T23:00:26.673 に答える
1

私は最近ElementTreeで遊んでいます。見てみましょう..

>>> from xml.etree import ElementTree
>>> help(ElementTree.ElementPath)
>>> root = ElementTree.fromstring("""
<root><child>One</child><child>Two</child><child>Three</child></root>
""")
>>> ElementTree.ElementPath.findall(root, "child")
[<Element child at 2ac98c0>, <Element child at 2ac9638>, <Element child at 2ac9518>]
>>> elements = ElementTree.ElementPath.findall(root, "child")
>>> two = [x for x in elements if x.text == "Two"]
>>> two[0].text
'Two'

これはあなたが探しているものですよね?ただし、ElementPath は xpath のサポートが制限されているだけですが、まったくサポートされていないとは言いません。

于 2008-10-27T09:32:36.830 に答える