2013-02-14 1 views
0

특정 구성 요소의 값을 가져오고 싶습니다. 예를 들어 아래 출력 (즉, 구성 요소 -> 이름 : paristrain 및 통계 -> TimeoutValue : 값)에서 2 개의 값만 가져 오려고합니다. xpath를 사용하여이 작업을 수행하려고했지만 원하는 출력을 얻을 수 없습니다. 이걸 좀 도와주세요.요소 트리를 사용하여 값 가져 오기

from xml.etree import ElementTree 

with open('rejexstats.xml', 'rt') as f: 
    tree = ElementTree.parse(f) 

for node in tree.iter(): 
    print node.tag, node.attrib 

이 인쇄 :

Statistics {} 
{http://www.rejex.com/stats}Server {'start': '2013-01-22T22:30:13.583', 'product': 'rejex', 'end': '2013-01-23T09:39:45.249', 'startup': '2013-01-22T22:30:13.583', 'name': 'localhost'} 
{http://www.rejex.com/statistics}Component {'subtype': 'Thread', 'type': 'Supplier', 'name': 'paristrain'} 
{http://www.rejex.com/statistics}Stat {'type': 'entry', 'name': 'TimeoutValue', 'value': '120'} 
{http://www.rejex.com/statistics}Stat {'type': 'entry', 'name': 'PendingRequests', 'value': '0'} 
{http://www.rejex.com/statistics}Stat {'type': 'entry', 'name': 'Session|0|SupplierTimeout', 'value': '0'} 
{http://www.rejex.com/statistics}Stat {'type': 'entry', 'name': 'Session|0|Errors', 'value': '0'} 
{http://www.rejex.com/statistics}Stat {'type': 'entry', 'name': 'Session|3|SupplierTimeout', 'value': '0'} 
{http://www.rejex.com/statistics}Stat {'type': 'entry', 'name': 'ApplyRulesErrors', 'value': '0'} 

XML 파일

<Statistics> 
    <Server end="2013-02-14T07:06:35.533" name="localhost" product="regex" start="2013-02-13T22:30:12.982" startup="2013-02-13T22:30:12.982"> 
     <Component name="paristrain" subtype="Thread" type="Supplier"> 
      <Stat name="TimeoutValue" type="entry" value="120"/> 
      <Stat name="PendingRequests" type="entry" value="0"/> 
      <Stat name="Session|0|SupplierTimeout" type="entry" value="0"/> 
      <Stat name="Session|0|Errors" type="entry" value="0"/> 
      <Stat name="Session|3|SupplierTimeout" type="entry" value="0"/> 
      <Stat name="ApplyRulesErrors" type="entry" value="0"/> 
      <Stat name="LateResponses" type="entry" value="0"/> 
      <Stat name="CacheTries" type="entry" value="0"/> 
      <Stat name="Session|4|Errors" type="entry" value="0"/> 
      <Stat name="MaxActiveThreads" type="entry" value="0"/> 
      <Stat name="MaxPendingQueueSize" type="entry" value="10"/> 
      <Stat name="ValidResponses" type="entry" value="0"/> 
      <Stat name="TranslateResponses" type="entry" value="0"/> 

답변

0

당신은 당신의 XPath 쿼리의 전체 네임 스페이스를 포함해야합니다 : 또는

for component in tree.iterfind('{http://www.rejex.com/statistics}Component'): 
    print component.attrib['name'] 

을, 당신은 사용할 수 있습니다 명시 적 네임 스페이스 매핑, ma PS 접두사 (선택한)는 URI를 네임 스페이스 :

nsmap = {'rej': 'http://www.rejex.com/statistics`} 

for stat in tree.iterfind('rej:Stat', namespaces=nsmap): 
    print stat.attrib['value'] 

rej 접두사 그런 다음 첫 번째 예에서 주어진 같은 XPath 쿼리로 변환, namespaces로 통과 어떤에서 조회됩니다. 당신은 {namespace} XPath는 규정에 확장 할 수 있습니다

더 복잡한 일치하는 항목을 찾을 수 있습니다 :

tree.find(
    "{http://www.rejex.com/statistics}Component[@name='paristrain']/" 
    "{http://www.rejex.com/statistics}Stat[@name='TimeoutValue']") 

예를 들어, 부모 name="paristrain" 속성을 가진 Component 요소 속성 name="TimeoutValue"이있는 Stat 요소를 반환해야합니다.

+0

물건은 내 XML 파일에 너무 많은 구성 요소가 있습니다. 구성 요소 paristrain 및 해당 TimeoutValue : Value 값을 가져 오는 데 관심이 있습니다. –

+0

@fear_matrix : 네임 스페이스 접두사를 사용하여 XPath 표현식을 만들 수 있습니다. –

+0

@fear_matrix : 테스트되지 않은 XPath식이 추가되었습니다. 샘플 XML을 포함하지 않았으므로이를 테스트 해보기가 어렵습니다. –