2016-07-22 106 views
0

一個複雜的XML我都有以下XML,解析在python lxml的解析器

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<Suite> 
<TestCase> 
    <TestCaseID>001</TestCaseID> 
    <TestCaseDescription>Hello</TestCaseDescription> 
    <TestSetup> 
    <Action> 
     <ActionCommand>gfdg</ActionCommand> 
     <TimeOut>dfgd</TimeOut> 
     <BamSymbol>gff</BamSymbol> 
     <Side>vfbgc</Side> 
     <PrimeBroker>fgfd</PrimeBroker> 
     <Size>fbcgc</Size> 
     <PMCode>fdgd</PMCode> 
     <Strategy>fdgf</Strategy> 
     <SubStrategy>fgf</SubStrategy> 
     <ActionLogEndPoint>fdgf</ActionLogEndPoint> 
     <IsActionResultLogged>fdgf</IsActionResultLogged> 
     <ValidationStep> 
     <IsValidated>fgdf</IsValidated> 
     <ValidationFormat>dfgf</ValidationFormat> 
     <ResponseEndpoint>gdf</ResponseEndpoint> 
     <ResponseParameterName>fdgfdg</ResponseParameterName> 
     <ResponseParameterValue>gff</ResponseParameterValue> 
     <ExpectedValue>fdgf</ExpectedValue> 
     <IsValidationResultLogged>gdfgf</IsValidationResultLogged> 
     <ValidationLogEndpoint>fdgf</ValidationLogEndpoint> 
     </ValidationStep> 
    </Action> 
    </TestCase> 
</Suite> 

的問題是我不能讓subparent標籤(validationStep)及其所有子值。任何人都可以幫忙

我的代碼:

import xml.etree.ElementTree as ET 
import collections 
t2 =[] 
v2 =[] 
test_case = collections.OrderedDict() 
tree = ET.parse('Action123.xml') 
root = tree.getroot() 

for testSetup4 in root.findall(".TestCase/TestSetup/Action"): 
    if testSetup4.find('ActionCommand').text == "gfdg": 
     for c1 in testSetup4: 
      t2.append(c1.tag) 
      v2.append(c1.text) 

     for k,v in zip(t2, v2): 
      test_case[k] = v 

請幫助我在這個問題上,我是新限於lxml解析器。

+0

您的xml無效。它缺少結束''。 –

+0

對不起!複製粘貼問題 – user2829222

回答

1

您沒有使用lxml,您當前正在使用Python標準庫中的xml.etree.ElementTree

如果你實際使用lxml,假設你安裝了它,您的導入更改爲:

import lxml.etree as ET 

然後,您可以檢查右側的XPath表達式內ActionCommand值:

for testSetup4 in root.xpath(".//TestCase/TestSetup/Action[ActionCommand = 'gfdg']"): 
    for c1 in testSetup4: 
     t2.append(c1.tag) 
     v2.append(c1.text) 

    for k, v in zip(t2, v2): 
     test_case[k] = v 
+0

謝謝。將試試:) – user2829222

0

如果我理解正確,您需要這樣的內容:

for testSetup4 in root.findall(".TestCase/TestSetup/Action"): 
    if testSetup4.find('ActionCommand').text == "gfdg": 
     for c1 in testSetup4:  
      if c1.tag != "ValidationStep": 
       t2.append(c1.tag) 
       v2.append(c1.text) 
      else: 
       for ch in c1: 
        t2.append(ch.tag) 
        v2.append(ch.text) 
+0

謝謝!將檢查它:) – user2829222

0

完成了。這裏是我的代碼:

for testSetup4 in root.findall(".TestCase/TestSetup/Action"): 
    if testSetup4.find('ActionCommand').text == "gfdg": 
     for c1 in testSetup4: 
      t1.append(c1.tag) 
      v1.append(c1.text) 

     for k,v in zip(t1, v1): 
      test_case[k] = v 

     valid = testSetup4.find('ValidationStep') 
     for c2 in valid: 
      t2.append(c2.tag) 
      v2.append(c2.text) 

     for k,v in zip(t2, v2): 
      test_case[k] = v