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

时间:2018-02-28 09:34:49

标签: python xml python-2.7

我有一个xml文件 - https://github.com/schogini/jVoiD/blob/master/Modules/jVoidCustomers/src/main/webapp/WEB-INF/spring/webcontext/DispatcherServlet-context.xml

我使用以下代码来解析xml文件 -

php bin/console cache:clear --env=dev --no-warmup
php bin/console cache:warmup --env=dev

我将程序的结果作为 -

 from lxml import etree
 xslt_root = etree.parse("/Users/cbuser1/CodeBlueFabricator/src/poc/PythonParser/mvc-config.xml")
 print(xslt_root)

现在我需要循环遍历此对象并获取其中每个元素的xpath。 (xml文件中的每个元素)。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

实际上我能够找到解决方案。我使用这个 -

将我的XML文件转换为JSON
flintlabel.config(text="Flint: "  + str(flint))

然后我浏览了json并找到了所有最里面的节点并使用它将它们的键和值保存在txt文件中 -

declare @t table (idx int, grp int, id int, data varchar(10));
insert into @t values  
       (001,    01,       01, null)      
     , (002,    01,       02, null)          
     , (003,    01,       03, 'Split')
     , (004,    01,       04, null)    
     , (005,    02,       01, null)           
     , (006,    02,       02, 'Split')
     , (007,    02,       03, null)    
     , (008,    02,       04, null)    
     , (009,    02,       05, null)    
     , (100,    03,       01, null)           
     , (101,    03,       02, null)    
     , (102,    03,       03, null)    
     , (103,    03,       04, 'Split')
     , (104,    03,       05, null);
with cte as 
(  select t.* 
        , count(*)     over (partition by t.grp) as cnt 
        , row_number() over (partition by t.grp order by t.id, t.idx) as rn 
        , (count(*) over (partition by t.grp) + t.id) as nwId  
        , ts.id as 'split' 
        , CASE WHEN t.id > ts.id THEN (count(*) over (partition by t.grp) + t.id + 2) 
                                 ELSE (count(*) over (partition by t.grp) + t.id) 
               end as nwnwId
     from @t t
     left join @t ts 
       on ts.grp = t.grp 
      and ts.data = 'split' 
)
select t.* 
 from cte t  
union all 
select t.idx, t.grp, t.id, null, t.cnt, t.rn, t.nwId, t.split, t.nwnwId + 1
 from cte t 
where t.data = 'split'
union all 
select t.idx, t.grp, t.id, null, t.cnt, t.rn, t.nwId, t.split, t.nwnwId + 2
 from cte t 
where t.data = 'split'
 order by grp, nwnwId, idx;

在第二个程序中,我浏览了由列表和字典组成的json,以进入最内层节点,这些节点仅包含一个键和一个值,而不包含其中的列表或字典。