私はとを使用Python
していlxml
ます。私のxmlファイル:
<Example>
<Path>
<Some.Node>
// ...
</Some.Node>
<Some.Node>
<Known.Node KnownAttribute="123"/>
<Some.Stuff>
<Nothing.Important>Bla</Nothing.Important>
</Some.Stuff>
<Relevant.Node>
<Property>
<Name>Some</Name>
<Value>True</Value>
</Property>
<Property>
<Name>Known.Name</Name>
<Value>Desired Value</Value>
</Property>
<Property>
<Name>Some.Other</Name>
<Value>Yes</Value>
</Property>
// ...
</Relevant.Node>
// ...
</Some.Node>
<Some.Node>
// ...
</Some.Node>
</Path>
</Example>
複数の<Some.Node>
ノードがあり、にKnownAttribute
等しいノードにのみ関心があり123
ます。私が得たこの部分:
query = "//Known.Node[@KnownAttribute='%s']" % attribute_value
ただし、<Relevant.Node>/<Property>/<Value>
where hasvalueの値を取得する必要が<Name>
ありますKnown.Name
。
これは私の最善の試みでしたが、うまくいきませんでした:
root = etree.parse(xml_file).getroot()
query = "//Known.Node[@KnownAttribute='%s']/..//Property[Name='Known.Name']/Value" % attribute_value
result = root.xpath(query)
print(result[0].text)
もちろん、印刷する必要がありますが、Desired Value
空の値/空白を返すだけです。
どうすれば必要な値を取得できますか?
あなたは本当に近いです。xpath式でノードのテキストを要求できます。
query = "//Known.Node[@KnownAttribute='%s']/..//" % attribute_value
query += "Property[Name='Known.Name']/Value/text()"
result = root.xpath(query)
print(result[0])
# prints:
Desired Value
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加