好的,我有一个情况,我需要将一个标签添加到给定 xpath 的某个其他标签。
示例 xml:
<?xml version="1.0" encoding="UTF-8"?>
<Assets>
<asset name="Adham">
<general>>
<services>
<land/>
<refuel/>
</services>
</general>
</asset>
<asset name="Test">
<general>
<Something/>
</general>
</asset>
</Assets>
我想向这两个资产添加
标签。但是,第二个资产缺少我想要添加的父
标记。每个资产标签都存储在一个变量中(例如node1、node2)。
我有以下 xpath: xpath1 = services/missions
,由于我的程序的工作方式,我不能简单地以不同的形式存储(即我没有地方存储 < code>services)
我需要检查任务标签是否已经存在,如果存在,则不执行任何操作。如果标签不存在,我需要创建它。如果它的父级不存在,我也需要创建它。
我怎样才能简单地使用 xpath 字符串来做到这一点?
编辑:我想将所有这些都基于布尔值:即 val = true,然后根据需要创建标签(和父级)。如果为 false,则删除标签。
(我没有其他方式来引用我需要的标签(因为我有一层又一层的函数来大规模地自动化这个过程,你可以在这里查看我之前的问题 Python Lxml:添加和删除标签))。
编辑编辑:另一个问题:
我没有包含要添加的元素的父级的变量,只有一个包含
对象的变量。我试图使用 xpath 和指向 ` 标记的变量来获取我想要的节点的父节点。
编辑编辑编辑:不要介意上面的内容,我将通过缩短 xpath 以指向父级并使用变量名称来引用每个项目来解决问题。
Ok, I have a case where I need to add a tag to a certain other tag given an xpath.
Example xml:
<?xml version="1.0" encoding="UTF-8"?>
<Assets>
<asset name="Adham">
<general>>
<services>
<land/>
<refuel/>
</services>
</general>
</asset>
<asset name="Test">
<general>
<Something/>
</general>
</asset>
</Assets>
I want to add a <missions>
tag to both assets. However, the second asset is missing the parent <services>
tag, which I want to add. Each asset tag is stored in a variable (say node1, node2).
I have the following xpath: xpath1 = services/missions
, which, due to the way my program works, I cannot simply store in a different form (i.e. i don't have a place to store just services
)
I need to check and see if the missions tag already exists, and, if so, do nothing. If the tag does not exist, I need to create it. If its parent does not exist, I need to create that too.
How can I do this simply by using the xpath string?
Edit: I want to base all this on a boolean value: i.e. val = true, then create tag (and parent) if neccesary. If false, then delete tag.
(I have no other way of referring to the tag I need (since I have layers on layers of functions to automate this process on a large scale, you can check out my previous question here Python Lxml: Adding and deleting tags)).
Edit edit: Another issue:
I don't have a variable containing the parent of the element to add, just a variable containing the <asset>
object. I am trying to get the parent of the node I want using the xpath and a variable pointing to the ` tag.
Edit edit edit: Never mind the above, I will fix the issue by shorting the xpath to point to the parent, and using a variable name to refer to each item.
发布评论
评论(1)
虽然我不确定是否将 add & 结合起来删除 1 个函数中的功能是个好主意,但无论如何这可能会按照您的预期工作。
Although I'm not sure that combining add & remove functionality in 1 function is good idea, but anyway this is likely to work as you're expecting.