2016-09-28 65 views
0

lxml或exml是否具有導出XML中所有xpath的功能?轉儲所有XPath

XML實例:

<note> 
    <to>Tove</to> 
    <from>Jani</from> 
    <heading>Reminder</heading> 
    <body> 
     <content>Don't forget me this weekend!</content> 
    </body> 
    </note> 

XPath的結果:

\\note 
\\note\to 
\\note\from 
\\note\heading 
\\note\body 
\\note\body\content 

回答

1

你必須遍歷樹,並調用每個節點上getpath

x = """<note> 
    <to>Tove</to> 
    <from>Jani</from> 
    <heading>Reminder</heading> 
    <body> 
     <content>Don't forget me this weekend!</content> 
    </body> 
    </note>""" 

from lxml import etree 
from StringIO import StringIO 
tree = etree.parse(StringIO(x)) 

paths = "\n".join(tree.getpath(n) for n in tree.iter()) 
print(paths) 

輸出:

/note 
/note/to 
/note/from 
/note/heading 
/note/body 
/note/body/content