Test.arxml内部的内容
<?xml version="1.0" encoding="utf-8"?>
<AUTOSAR xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://autosar.org/schema/r4.0" xsi:schemaLocation="http://autosar.org/schema/r4.0 AUTOSAR_4-2-1.xsd">
<AR-PACKAGES>
<AR-PACKAGE>
<SHORT-NAME>AUTOSAR</SHORT-NAME>
</AR-PACKAGE>
<AR-PACKAGE>
<SHORT-NAME>BALL</SHORT-NAME>
</AR-PACKAGE>from lxml import etree
from lxml import objectify
from lxml.etree import fromstring
tree = objectify.parse('Test.arxml')
root = tree.getroot()
namespaces = {}
namespaces['ar'] = root.nsmap[None]
xpath = './/ar:AR-PACKAGE/ar:SHORT-NAME'
hits = root.xpath(xpath, namespaces=namespaces)命中的现状
new_element_string = "<AR-PACKAGE xmlns:None='http://autosar.org/schema/r4.0'><SHORT-NAME xmlns:None='http://autosar.org/schema/r4.0'></SHORT-NAME>{0}</AR-PACKAGE>".format("AUTOSAR_Platform")
new_element_node = node = objectify.fromstring(new_element_string)
root['AR-PACKAGES'].append(new_element_node)
second_hits = root.xpath(xpath, namespaces=namespaces)命中的现状
问:为什么“AUTOSAR_Platform”不被视为second_hits中的第三个包?
发布于 2021-04-22 17:08:43
在所附加的节点中,您的文本出现在错误的位置。你可能想
new_element_string = "<AR-PACKAGE xmlns:None='http://autosar.org/schema/r4.0'><SHORT-NAME xmlns:None='http://autosar.org/schema/r4.0'></SHORT-NAME>{0}</AR-PACKAGE>".format("AUTOSAR_Platform")成为
new_element_string = "<AR-PACKAGE xmlns:None='http://autosar.org/schema/r4.0'><SHORT-NAME xmlns:None='http://autosar.org/schema/r4.0'>{0}</SHORT-NAME></AR-PACKAGE>".format("AUTOSAR_Platform")然后使名称空间匹配:
new_element_string = "<AR-PACKAGE xmlns='http://autosar.org/schema/r4.0'><SHORT-NAME>{0}</SHORT-NAME></AR-PACKAGE>".format("AUTOSAR_Platform")https://stackoverflow.com/questions/67214839
复制相似问题