在python中解析xml以查找所有元素(节点)的xpath

问题描述 投票:1回答:1

我有一个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文件中的每个元素)。有任何想法吗?

python xml python-2.7
1个回答
0
投票

实际上我能够找到解决方案。我使用以下方法将我的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,以进入最内层节点,这些节点仅包含一个键和一个值,而不包含其中的列表或字典。

© www.soinside.com 2019 - 2024. All rights reserved.