在使用lxml时在python中使用命名空间解析XML时遇到问题

时间:2015-02-20 07:46:33

标签: python lxml elementtree

我正在尝试在XML的层次结构中深入访问和修改标记。我已经使用了很多选项来实现它。请帮我查看和修改标签。这是我的XML:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cre="http://www.code.com/abc/V1/createCase">
   <soapenv:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/2" xmlns:wsu="http://docs.oasis-open.org/a.xsd"></wsse:Security>
   </soapenv:Header>
   <soapenv:Body xmlns:wsu="http://docs.oasis-open.org/30.xsd" wsu:Id="id-14">
      <cre:createCase>
         <cre:Request>
            <cre:ServiceAttributesGrp>
               <cre:MinorVer>?</cre:MinorVer>
            </cre:ServiceAttributesGrp>
            <cre:CreateCaseReqGrp>
               <cre:Language>English</cre:Language>
               <cre:CustFirstNm>Issue</cre:CustFirstNm>
               <cre:CustLastNm>Detection</cre:CustLastNm>
               <cre:AddlDynInfoGrp>
                  <cre:AddlDynInfo>
                           <cre:FieldNm>TM3</cre:FieldNm>
                           <cre:FieldVal></cre:FieldVal>
                  </cre:AddlDynInfo>
                  <cre:AddlDynInfo>
                           <cre:FieldNm>PM417</cre:FieldNm>
                           <cre:FieldVal>Not Defined</cre:FieldVal>
                  </cre:AddlDynInfo>
               </cre:AddlDynInfoGrp>
               <cre:CreateCriteriasGrp>
                  <cre:CreateCriterias>
                     <cre:CriteriaNm>CriticalReqDtlValidationReqd</cre:CriteriaNm>
                  </cre:CreateCriterias>
               </cre:CreateCriteriasGrp>
            </cre:CreateCaseReqGrp>
         </cre:Request>
      </cre:createCase>
   </soapenv:Body>
</soapenv:Envelope>

我必须在“AddlDynInfo”标签中访问和修改“FieldVal”标签的值,其中“FieldNm”标签值的对应值是“PM417”(因为有两个“AddlDynInfo”标签出现。 截至目前,我只是在父标签上,因为我无法访问它:

tree = etree.parse(template_xml)
root = tree.getroot()
for msgBody in root[1]:
  for createCase in msgBody:
    for request in createCase:
     print request
     for CreateCaseReqGrp in request.findall('{cre}CreateCaseReqGrp',namespaces=root.nsmap):
     print CreateCaseReqGrp

1 个答案:

答案 0 :(得分:1)

定义namespaces and XPaths使这很容易。你的情况是这样的:

ns = {
    'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/',
    'cre': 'http://www.code.com/abc/V1/createCase'
}

for casereq in root.xpath(
    'soapenv:Body/cre:createCase/cre:Request/'
    'cre:CreateCaseReqGrp/cre:AddlDynInfoGrp/cre:AddlDynInfo', namespaces=ns):
    print casereq.xpath('cre:FieldNm/text()', namespaces=ns)
    print casereq.xpath('cre:FieldVal/text()', namespaces=ns)