[英]Parsing an xml in python to find xpaths of all elements (nodes)
我有一个xml文件-https ://github.com/schogini/jVoiD/blob/master/Modules/jVoidCustomers/src/main/webapp/WEB-INF/spring/webcontext/DispatcherServlet-context.xml
我正在使用以下代码来解析xml文件-
from lxml import etree
xslt_root = etree.parse("/Users/cbuser1/CodeBlueFabricator/src/poc/PythonParser/mvc-config.xml")
print(xslt_root)
我得到我的程序的结果为-
<lxml.etree._ElementTree object at 0x10e95bcc8>
现在,我需要遍历该对象并获取其中每个元素的xpath。 (xml文件中的每个单个元素)。 有任何想法吗?
实际上,我能够找到解决方案。 我使用以下代码将XML文件转换为JSON:
import json
import xmltodict
with open("INSERT XML FILE LOCATION HERE", 'r') as f:
xmlInString = f.read()
print("The xml file read-")
print(xmlInString)
JsonedXML = json.dumps(xmltodict.parse(xmlString), indent=4)
print("\nJSON format of read xml file-")
print(JsonedXML)
with open("myJson.json", 'w') as f:
f.write(JsonedXML)
然后我遍历json,找到所有最里面的节点,并使用以下命令将其键和值保存在txt文件中:
import json
data = json.load(open('GIVE LOCATION OF THE CONVERTED JSON HERE'))
token_key_value_dictionary=[]
only_tokens_dictionary=[]
uniqueKey ='xml'
def recursive_json_parser(start_point_value,uniqueKey,start_point_key=''):
if start_point_key !='':
uniqueKey += '.'+start_point_key
if type(start_point_value) is str or type(start_point_value) is unicode:
token_key_value_dictionary.append([str(uniqueKey),str(start_point_value)])
only_tokens_dictionary.append(str(start_point_value))
uniqueKey =''
elif type(start_point_value) is list:
for i in start_point_value:
recursive_json_parser(i,uniqueKey)
else:
for key,value in start_point_value.items():
recursive_json_parser(value,uniqueKey,key)
for key,value in data.items():
print (len(value))
recursive_json_parser(value,uniqueKey,key)
f = open('tokens.txt','w')
for row in only_tokens_dictionary:
print (row)
if row!='':
f.write(row+'\n')
f.close()
在第二个程序中,我遍历了列表的json-consisting和字典,以到达仅由键和值组成的最里面的节点,而其中没有更多的列表或字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.