2011-01-25 7 views
0

xml出力を別のプログラムで解析しています。ここでPythonのxml要素からデータを取得する際に問題が発生する

は、XMLフラグメントの例です:

<result test="Passed" stamp="2011-01-25T12:40:46.166-08:00"> 
     <assertion>MultipleTestTool1</assertion> 
     <comment>MultipleTestTool1 Passed</comment> 
     </result> 

私は<comment>要素からデータを取得したいです。ここで

は私のコードスニペットです:

import xml.dom.minidom 
mydata.cnodes = mydata.rnode.getElementsByTagName("comment")       
    value = self.getResultCommentText(mydata.cnodes 

    def getResultCommentText(self, nodelist): 
      rc = [] 
      for node in nodelist: 
       if node.nodeName == "comment": 
        if node.nodeType == node.TEXT_NODE: 
         rc.append(node.data) 

     return ''.join(rc) 

値は常に空であり、のnodeTypeが常にELEMENT_NODEであるので、.dataが、私は、Pythonに新しいですが存在しない、これは私を引き起こしていることが表示されます私の頭を傷つける。誰かが私が間違っていることを教えてもらえますか?ここ

答えて

0

あなたは以下のとおりです。

>>> from lxml import etree 
>>> result = """ 
... <result test="Passed" stamp="2011-01-25T12:40:46.166-08:00"> 
...   <assertion>MultipleTestTool1</assertion> 
...   <comment>MultipleTestTool1 Passed</comment> 
...  </result> 
... """ 
>>> xml = etree.fromstring(result) 
>>> xml.xpath('//comment/text()') 
['MultipleTestTool1 Passed'] 
>>> 
1

ではなくminidomのElementTreeのを試してみてください:

>>> import xml.etree.cElementTree as et 
>>> data = """ 
... <result test="Passed" stamp="2011-01-25T12:40:46.166-08:00"> 
...   <assertion>MultipleTestTool1</assertion> 
...   <comment>MultipleTestTool1 Passed</comment> 
...  </result> 
... """ 
>>> root = et.fromstring(data) 
>>> root.tag 
'result' 
>>> root[0].tag 
'assertion' 
>>> root[1].tag 
'comment' 
>>> root[1].text 
'MultipleTestTool1 Passed' 
>>> root.findtext('comment') 
'MultipleTestTool1 Passed' 
>>> 
0

はminidomを使用し続けると、私は必要な方法を示すために、あなたのコードスニペットを変更した:

import xml.dom.minidom 
mydata.cnodes = mydata.rnode.getElementsByTagName("comment") 
value = self.getResultCommentText(mydata.cnodes) 
    def getResultCommentText(self, nodelist): 
    rc = [] 
    for node in nodelist: 
     # Since the node list was created by getElementsByTagName("comment"), 
     # all nodes in this list will be comment nodes. 
     # 
     # The text data required is a child of the current node 
     for child in node.childNodes: 
     # If the current node is a text node, append it's information 
     if child.nodeType == child.TEXT_NODE: 
      rc.append(child.data) 
    return ''.join(rc) 

基本的には、必要なテキストデータがテキストノード内に含まれています。コメントノードの子です。まず、ノードを取得してからデータを取得する必要があります。

関連する問題