Python小工具分享:
用python自带的ElementTree工具导出应用层模块ARXML中的S/R ports,方便模块工程师更新APPInterface。
网上关于xml的资料很多,但例子都太简单,直接引用需要先好好理解xml结构,之前花时间琢磨了下,记录一下两种方法。
1 通过标签名识别Ports
import xml.etree.ElementTree as ET
# 获取 XML 文档对象 ElementTree
tree = ET.parse('test.arxml')
# 获取 XML 文档对象的根结点 Element
root = tree.getroot()
# 打印根结点的名称
print("根节点的名称:", root.tag)
# 获取其他属性
print('root的属性:', root.attrib)
for child in root:
print ("遍历root的下一层", child.tag, "----", child.attrib)
#根据标签名查找root下的所有标签
captionList = root.findall("R-PORT-PROTOTYPE") #在当前指定目录下遍历
captionList1 = root.findall("P-PORT-PROTOTYPE") #在当前指定目录下遍历
print("RPORT一共有:", len(captionList))
print("PPORT一共有:", len(captionList1))
#for UUID in RPORTS
# name = stu.getElementsByTagName('SHORT-NAME')[0].childNodes[0].nodeValue
#print(root[0].tag, root[0][0].text)
for caption in captionList:
print(caption[0].text)
print (20 * "*")
for caption in captionList1:
print(caption[0].text)
2 通过标签路径识别Ports
import xml.etree.ElementTree as ET
# 获取 XML 文档对象 ElementTree
tree = ET.parse('1.arxml')
# 获取 XML 文档对象的根结点 Element
root = tree.getroot()
# 打印根结点的名称
print("根节点的名称:", root.tag)
# 获取其他属性
print('root的属性:', root.attrib)
for child in root:
print ("遍历root的下一层", child.tag, "----", child.attrib)
#根据标签名查找root下的所有标签
#通过标签路径来查找目标标签
captionList = root.findall("AR-PACKAGE/AR-PACKAGES/AR-PACKAGE/ELEMENTS/APPLICATION-SW-COMPONENT-TYPE/PORTS/R-PORT-PROTOTYPE") #在当前指定目录下遍历
captionList1 = root.findall("AR-PACKAGE/AR-PACKAGES/AR-PACKAGE/ELEMENTS/APPLICATION-SW-COMPONENT-TYPE/PORTS/P-PORT-PROTOTYPE") #在当前指定目录下遍历
print("RPORT一共有:", len(captionList))
print("PPORT一共有:", len(captionList1))
#找不到标签会返回空列表
# 根据每一个父标签去找目标标签:SHORT-NAME
for RPORTS in captionList:
RPORTS_NAME_tag = RPORTS.findall("SHORT-NAME")[0]
RPORTS_NAME = RPORTS_NAME_tag.text #字典
print(RPORTS_NAME)
print (20 * "*")
print (20 * "*")
for PPORTS in captionList1:
PPORTS_NAME_tag = PPORTS.findall("SHORT-NAME")[0]
PPORTS_NAME = PPORTS_NAME_tag.text
print(PPORTS_NAME)
结果如下
根节点的名称: AR-PACKAGES
root的属性: {}
遍历root的下一层 AR-PACKAGE ---- {'UUID': 'ac1b3980-acdc-589e-5e9c-30f924191f5f'}
RPORT一共有: 208
PPORT一共有: 76
gASI_u8SSBSw1
gASI_u8SSBSw2_InterCore
gASI_bKLRSw
gASI_bKL15Sw
gASI_bClutchSw
gANC_bDrvrDoorOpenSts
gANC_bFrtPsngDoorOpenSts
gANC_bRLDoorOpenSts
gANC_bRRDoorOpenSts