首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在树中添加Lxml对象时,在lxml树中找不到lxml对象。

在树中添加Lxml对象时,在lxml树中找不到lxml对象。
EN

Stack Overflow用户
提问于 2021-04-22 14:03:36
回答 1查看 49关注 0票数 0

Test.arxml内部的内容

代码语言:javascript
复制
<?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>
代码语言:javascript
复制
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)

命中的现状

代码语言:javascript
复制
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中的第三个包?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-22 17:08:43

在所附加的节点中,您的文本出现在错误的位置。你可能想

代码语言:javascript
复制
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")

成为

代码语言:javascript
复制
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")

然后使名称空间匹配:

代码语言:javascript
复制
new_element_string = "<AR-PACKAGE xmlns='http://autosar.org/schema/r4.0'><SHORT-NAME>{0}</SHORT-NAME></AR-PACKAGE>".format("AUTOSAR_Platform")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67214839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档