一、前言
读取带命名空间的arxml,最好的方式是创建一个字典来存放你自己的前缀并在搜索函数中使用它们:
二、解读如下ns.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<AUTOSAR xmlns="http://autosar.org/schema/r4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://autosar.org/schema/r4.0 AUTOSAR_00048.xsd">
<AR-PACKAGES>
<AR-PACKAGE UUID="20edd97b-a511-418b-8af0-9c83b001a409">
<SHORT-NAME>ARRoot</SHORT-NAME>
<ELEMENTS>
<IMPLEMENTATION-DATA-TYPE UUID="621bef99-52d0-4796-b35c-0b4481bdb90d">
<SHORT-NAME>U8</SHORT-NAME>
<CATEGORY>VALUE</CATEGORY>
<SW-DATA-DEF-PROPS>
<SW-DATA-DEF-PROPS-VARIANTS>
<SW-DATA-DEF-PROPS-CONDITIONAL>
<BASE-TYPE-REF DEST="SW-BASE-TYPE">/ARRoot/uint8</BASE-TYPE-REF>
</SW-DATA-DEF-PROPS-CONDITIONAL>
</SW-DATA-DEF-PROPS-VARIANTS>
</SW-DATA-DEF-PROPS>
<IS-STRUCT-WITH-OPTIONAL-ELEMENT>false</IS-STRUCT-WITH-OPTIONAL-ELEMENT>
</IMPLEMENTATION-DATA-TYPE>
<SW-BASE-TYPE UUID="9dde1c1b-110e-4b23-9dd6-0e78620c0005">
<SHORT-NAME>uint8</SHORT-NAME>
<CATEGORY>FIXED_LENGTH</CATEGORY>
<BASE-TYPE-SIZE>8</BASE-TYPE-SIZE>
<BASE-TYPE-ENCODING>NONE</BASE-TYPE-ENCODING>
</SW-BASE-TYPE>
</ELEMENTS>
</AR-PACKAGE>
</AR-PACKAGES>
</AUTOSAR>
三、读取代码
import xml.etree.ElementTree as ET
ns = {'real_person': 'http://people.example.com',
'role': 'http://characters.example.com'}
tree = ET.parse('ns.xml')
root = tree.getroot()
for actor in root.findall('real_person:actor', ns):
name = actor.find('real_person:name', ns)
print(name.text)
for char in actor.findall('role:character', ns):
print(' |-->', char.text)
读取带命名空间的arxml文件
import xml.etree.ElementTree as ET
arxml_namespace= {
'arxmlns' : "http://autosar.org/schema/r4.0",
'xmlns:xsi' : 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:chemaLocation' : "http://autosar.org/schema/r4.0 AUTOSAR_4-0-0.xsd"}
tree = ET.parse('ns_test.arxml')
root = tree.getroot()
for actor in root.findall(".//arxmlns:PORTS/arxmlns:R-PORT-PROTOTYPE", arxml_namespace):
name = actor.find('./arxmlns:SHORT-NAME', arxml_namespace)
print(name.text)
读取结果: