سؤال

جديد إلى XML. أبحث عن XPath لبحث ملف XML مع الثعبان شكل ElementTree

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

وللقيام بالبحث عن الطفل مع "اثنين" والعودة صح / خطأ

وإذا بدأ تشغيله مثل

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

وكيف يمكن أن يتحقق هذا

هل كانت مفيدة؟

المحلول

ولقد لعب مع 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 التالية:

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

وكانت النتيجة على صحيح ، أو إذا كان مثل هذا العنصر (طفل من العنصر العلوي بحيث قيمة السلسلة التي تساوي "اثنان") موجودا،

و كاذبة وإلا.

والأمل ساعد هذا.

وابتهاج،

وDimitre Novatchev

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top