2014-02-05 58 views
1

我想從命令行參數中讀取XML文件。一般來說,我是使用libxml2和XPath的新手。我想用XPath查詢。Python libxml2:使用xpath查詢xml

XML:

<?xml version="1.0"?>                                  
<xmi:XMI xmlns:cas="http:///text/cas.ecore" xmlns:audioform="http:something" xmlns:xmi="http://blahblah" xmlns:lib="http://blahblah" xmlns:solr="http:blahblah" xmlns:tcas="http:///blah" xmi:version="2.0">             
    <cas:NULL xmi:id="0"/>                                  
    <cas:Sofa xmi:id="9" Num="1" ID="First" Type="text" String="play a song"/>  
    <cas:Sofa xmi:id="63" Num="2" ID="Second" Type="text" String="Find a contact"/>  
    <cas:Sofa xmi:id="72" Num="3" ID="Third" Type="text" String="Send a message"/>  
    <lib:Confidence xmi:id="1" sofa="9" begin="0" end="1" key="context" value="" confidence="1.0"/>                   
</xmi:XMI> 

代碼:

def main(argv): 
    try: 
    xmlfile=argv[0] 
    doc=libxml2.parseFile(xmlfile) 
    root2=doc.children 

    print root2 # This prints everything but <?xml version="1.0"?> 
    result= root2.xpathEval("//*") 

    for node in result: 
     print node 
     print node.nodePath(), node.name, node.content 

我想走得更遠,做使用此文件某種處理。

  1. 如何使用xpath獲得像63這樣的值?從xmi:id="63"
  2. 查找字符串,其中xmi:id = "72"。結果應該是「發送消息」
  3. 查找字符串,其中xmi:id = 72 and ID= "Third"。結果應該是「發送消息」
  4. 我使用node.Path()node.namenode.content此節點嘗試:

    <cas:Sofa xmi:id="9" Num="1" ID="First" Type="text" String="play a song"/> 
    

    的結果是:/xmi:XMI/cas:Sofa[1]nodePath()沙發姓名和印刷品沒有內容

我該如何去得到1和2和3?

回答

1

關於命名空間:

>>> from lxml import etree 
>>> doc = etree.parse('in.html') 
>>> names = {'cas':'http:///text/cas.ecore', 'xmi': 'http://blahblah'} 
>>> doc.xpath('//cas:Sofa[@xmi:id="63"]', namespaces=names) 
[<Element {http:///text/cas.ecore}Sofa at 0x10550a5f0>] 
>>> doc.xpath('//cas:Sofa[@xmi:id="63"]/@String', namespaces=names) 
['Find a contact'] 
>>> doc.xpath('//cas:Sofa[@xmi:id="72" and @ID="Third"]/@String', namespaces=names) 
['Send a message'] 
+0

嗨,Guy,你可以給出程序的前幾行:ttributeError : 'ElementTree的' 對象有沒有屬性 '的XPath' 如何完成這個:'高清主(argv的):' elem_list = [] elem_num = 0 嘗試: XMLFILE =的argv [0] DOC = ET。解析(xmlfile) root = doc。getroot() for root in root:' – user1189851

+0

已更新,另請參閱http://lxml.de/xpathxslt.html#namespaces-and-prefixes –

+0

好吧,適合我(Python 3.3.3) –

0

我不熟悉Python,但下面的XPath應該做的:

1)//*/@xmi:id

2)//*[@xmi:id='72']/@String

3)//*[@xmi:id='72' and @ID='Third']/@String

屬性選擇與@,在括號中創建條件([])。

請注意,您的XML使用命名空間。您應該考慮更具體的XPath(/xmi:XMI/cas:Sofa)並使用命名空間管理器,而不是僅選擇所有內容(//*)。

+0

謝謝,但你能給我一個完整的命令,只知道如果我錯過什麼。我得到一個xmlXpathEval()失敗的錯誤。 :(Coul dI在每個節點上使用xpath? – user1189851

+0

似乎libxml2已經過時了,我無法在我的機器上工作...... –