2012-10-19 3 views
1
import xml.dom.minidom 

document = """\ 
<parent> 
    <child1>value 1</child1> 
    <child2>value 2</child2> 
    <child3>value 3</child3> 
</parent> 
""" 

def getText(nodelist): 
    rc = [] 
    for node in nodelist: 
     if node.nodeType == node.TEXT_NODE: 
      rc.append(node.data) 
     else: 
      print "not text: "+ node.toxml() 

    return ''.join(rc) 

def handleParent(family): 
    handleChild(family.getElementsByTagName("parent")[0]) 

def handleChild(parent): 
    print getText(parent.childNodes) 

dom = xml.dom.minidom.parseString(document) 
handleParent(dom) 

이 코드가 하위 태그 사이의 값을 가져 오지 않는 이유는 누구에게 말해 줄 수 있습니까? 도움을파이썬 미니 노드 노드 데이터에 액세스

not text: <child1>value 1</child1> 
not text: <child2>value 2</child2> 
not text: <child3>value 3</child3> 

감사 :이 여기 http://docs.python.org/library/xml.dom.minidom.html

에서 옷을 벗었 예이다이 출력입니다.

답변

0

한 단계 더 깊이 들어가야합니다. 텍스트는 <childN>의 하위 항목입니다.

def getText(nodelist): 
    rc = [] 
    for outer in nodelist: 
     for node in outer.childNodes: 
      if node.nodeType == node.TEXT_NODE: 
       rc.append(node.data) 
      else: 
       print "not text: "+ node.toxml() 

    return ''.join(rc) 
+0

굉장합니다. 그거야. – user1760089