gpt4 book ai didi

python - 使用 lxml 时,在 python 中使用 namespace 解析 XML 时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:54 26 4
gpt4 key购买 nike

我正在尝试访问和修改 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”标 checkout 现两次。截至目前,我仅停留在父标签上,因为我无法访问它:

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

最佳答案

定义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)

关于python - 使用 lxml 时,在 python 中使用 namespace 解析 XML 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28623918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com