我的 XML1 如下所示,其中放置了所有相等的運算子語法:
<Operator>
<Equal>
<Data>Object</Data>
<Data>1</Data>
</Equal>
<Equal>
<Integer>Non_Object</Integer>
<Integer>2</Integer>
</Equal>
</Operator>
我的 XML2 如下,我必須檢查相等運算子的語法,即如果任何具有相等運算子的標簽具有兩個資料或兩個整數或(如 XML1 所示),那么它將給出標簽的名稱
XML2:
<File>
<Sub_Function_1>
<Messages>
<Data>
<Label>Alarm</Label>
<Value>
<Equal>
<Data>Yes</Data>
<Integer>80</Integer>
</Equal>
</Value>
</Data>
</Messages>
</Sub_Function_1>
<Sub_Function_2>
<Services_1>
<Data>
<Label>Hotel</Label>
<Value>
<Equal>
<Data>Yes</Data>
<Data>2</Data>
</Equal>
</Value>
</Data>
</Services_1>
<Services_2>
<Data>
<Label>Food</Label>
<Value>
<Equal>
<Integer>Yes</Integer>
<Integer>2</Integer>
</Equal>
</Value>
</Data>
</Services_2>
</Sub_Function_2>
</File>
所以在 XML2 標簽“酒店”和“食物”匹配 XML1 中存在的相等運算子的語法
那么如何列印這兩個標簽。
我開始我的代碼只是先搜索所有相等運算子,但我沒有得到如何匹配 XML2 中給定 XML1 的相等運算子的語法
from lxml import etree
doc = etree.parse('C:/Syntax/Sample.xml')
doc2 = etree.parse('C:/Syntax/Project.xml')
for op in doc.findall('.//Equal'):
for eq in doc2.findall('.//File'):
match = eq.findall('.//Equal')
for ch in match :
ch = match.find('Data')
ch = match.find('Data')
我只想在 XML1 中找到具有語法的標簽。
永遠感謝任何形式的幫助。
uj5u.com熱心網友回復:
如果我理解您的問題以及您的 xml 檔案的結構,那么這應該可以正常作業:
#identify your values in the first file
values = [e.xpath('.//*[2]')[0].text for e in doc.xpath('.//Equal')]
#find corresponding values in the Sub_Function_2 element children in the 2nd file
for service in doc2.xpath('.//Sub_Function_2//Data[Label]'):
value = service.xpath('.//Equal//*[2]/text()')[0]
if value in values:
#get the value in the corresponding Label
print(service.xpath('.//Label/text()')[0])
根據您的示例 xml,輸出應為:
Hotel
Food
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521256.html
上一篇:如何在不使用phpdom覆寫的情況下在xml中添加子項?
下一篇:使用lxml從XML匯入資料
