获取基于特定标签的文本父属性 - XML
问题描述:
我有一个XML文件,如下所示:获取基于特定标签的文本父属性 - XML
<customer>
<customerdetails id="80">
<account id="910">
<attributes>
<premium>true</premium>
<type>mpset</type>
</attributes>
</account>
<account id="911">
<attributes>
<premium>true</premium>
<type>spset</type>
</attributes>
</account>
</customerdetails>
</customer>
需要解析的文件,并从同一获得必要的细节,我有使用了python的lxml库。
使用我可以从XML文件中获取详细信息,例如,我可以从文件的特定标记中获取文本。
from lxml import etree
def read_a_customer_section(self):
root = self.parser.getroot()
customer_id = "80"
account_id = "910"
type_details = root.findtext("customerdetails[@id='"+customer_id+"']/account[@id='"+account_id+"']/attributes/type")
print type_details
dd = ConfigParserLxml("dummy1.xml").read_a_customer_section()
使用这个我可以得到预期的特定标签的文本。
但现在我需要基于文本获取父标签属性。
例如,如果我给类型“mpset”作为输入,我应该能够得到 “账户”的属性,此外,我需要找到“为CustomerDetails” 属性。
有人帮我一样。
希望这个很清楚,否则让我知道我会尽量使它更清楚。
答
In [3]: tree.xpath('//account[.//type="mpset"]/@id')
Out[3]: ['910']
OR:
In [4]: tree.xpath('//*[.//type="mpset"]/@id')
Out[4]: ['80', '910'] # this will return all the id attribute.
//
后代或根节点的自。
.
当前节点
.//
后代或当前节点的自我。
.//type="mpset"
当前节点的后代标签类型的字符串值是mpset
@id
得到id
属性
*
是通配符,匹配任何标签
如果你不介意,你能解释一下它是如何工作的? – Murali
@只是简单的xpath。我会更新我的答案。 –