解析NCPDP格式的XML

时间:2018-11-15 08:01:58

标签: python xml xml-namespaces elementtree

我想在python中解析xml以下。如果有任何错误,那么我想用描述代码和描述提取该信息

xml为NCPDP格式。我想从下面的xml中获取描述代码和描述。

<transport:Message StructuresVersion="2014041" ECLVersion="2014041" DatatypesVersion="2014041" TransactionDomain="SCRIPT" PA-StructuresVersion="2014041" TransactionVersion="2014041" TransportVersion="2014041" 
xsi:schemaLocation="http://www.ncpdp.org/schema/transport transport.xsd" 
xmlns:transport="http://www.ncpdp.org/schema/transport" 
xmlns:datatypes="http://www.ncpdp.org/schema/datatypes" 
xmlns:script="http://www.ncpdp.org/schema/script" 
xmlns:structures="http://www.ncpdp.org/schema/structures" 
xmlns:pa-structures="http://www.ncpdp.org/schema/pa-structures" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<transport:Header>
    <transport:To Qualifier="C">123456</transport:To>
    <transport:From Qualifier="ZZZ">PAYER123</transport:From>
    <transport:MessageID>ab29d6cd563b43f09e7519314fef0b8d</transport:MessageID>
    <transport:RelatesToMessageID>ab29d6cd563b43f09e7519314fef0b8d</transport:RelatesToMessageID>
    <transport:SentTime>2018-11-15T07:28:34.1539289Z</transport:SentTime>
    <transport:SenderSoftware>
        <transport:SenderSoftwareDeveloper>quanti</transport:SenderSoftwareDeveloper>
        <transport:SenderSoftwareProduct>quanti</transport:SenderSoftwareProduct>
        <transport:SenderSoftwareVersionRelease>1.0</transport:SenderSoftwareVersionRelease>
    </transport:SenderSoftware>
    <transport:TestMessage>1</transport:TestMessage>
</transport:Header>
<transport:Body>
    <transport:Error>
        <transport:Code>601</transport:Code>
        <transport:DescriptionCode>500</transport:DescriptionCode>
        <transport:Description>XML Validation Error: The 'http://www.ncpdp.org/schema/datatypes:Number' element is invalid - The value 'None' is invalid according to its datatype 'http://www.ncpdp.org/schema/datatypes:n1..10' - The Pattern constraint failed.</transport:Description>
    </transport:Error>
</transport:Body>

我在下面尝试过

import xml.etree.ElementTree as ET 
tree = ET.parse('parse.xml') 
root = tree.getroot() 
for child in root: 
    print(child.tag) 
    print("_______")

1 个答案:

答案 0 :(得分:0)

  

如果有任何错误,那么我想用   说明代码和说明

这应该让您入门...

Python

import xml.etree.ElementTree as ET

tree = ET.parse('parse.xml')

ns = {"tr": "http://www.ncpdp.org/schema/transport"}

for error in tree.findall("./tr:Body/tr:Error", ns):
    print(f"ERROR CODE: {error.find('./tr:Code', ns).text}\n"
          f"ERROR DESCRIPTION: {error.find('./tr:Description', ns).text}")

输出

ERROR CODE: 601
ERROR DESCRIPTION: XML Validation Error: The 'http://www.ncpdp.org/schema/datatypes:Number' element is invalid - The value 'None' is invalid according to its datatype 'http://www.ncpdp.org/schema/datatypes:n1..10' - The Pattern constraint failed.

有关更多信息,请参见the documentation