简体   繁体   English

如何将 append 数据解析为 XML object - ZA7F5F35426B9272111FC9231B5Z3

[英]How to append data to a parsed XML object - Python

I am trying to take an xml document parsed with lxml objectify in python and add subelements to it.我正在尝试在 python 中获取用lxml objectify解析的 xml 文档并向其中添加子元素。

The problem is that I can't work out how to do this.问题是我无法弄清楚如何做到这一点。 The only real option I've found is a complete reconstruction of the data with objectify.Element and objectify.SubElement , but that... doesn't make any sense.我发现的唯一真正的选择是使用objectify.Elementobjectify.SubElement完全重建数据,但这......没有任何意义。

With JSON for instance, I can just import the data as an object and navigate to any section and read, add and edit data super easily.以 JSON 为例,我可以将数据导入为 object 并导航到任何部分并超级轻松地读取、添加和编辑数据。

How do I parse an xml document with objectify so that I can add subelement data to it?如何使用objectify解析 xml 文档,以便向其中添加子元素数据?

data.xml

<?xml version='1.0' encoding='UTF-8'?>
<data>
  <items>
    <item> text_1 </item>
    <item> text_2 </item>
  </items>
</data>

I'm sure there is an answer on how to do this online but my search terminology is either bad or im dumb, but I can't find a solution to this question.我确信有关于如何在线执行此操作的答案,但我的搜索术语要么不好,要么很愚蠢,但我找不到这个问题的解决方案。 I'm sorry if this is a duplicate question.如果这是一个重复的问题,我很抱歉。

I guess it has been quite difficult explain the question, but the problem can essentially be defined by an ambiguity with how .Element and .SubElement can be applied.我想解释这个问题相当困难,但问题本质上可以由如何应用.Element.SubElement的模糊性来定义。

This reference contains actionable and replicable ways in which one can append or add data to a parsed XML file.此参考包含可操作和可复制的方法,其中可以appendadd数据添加到已解析的 XML 文件。

Solving the key problem of:解决关键问题:

How do I reference content in a nested tag without reconstructing the entire tree?如何在不重建整个树的情况下引用嵌套标签中的内容?

The author uses the find feature , which is called with root.findall(./tag)作者使用了find 功能,用root.findall(./tag)调用

This allows one to find the nested tag that they wanted without having to reconstruct the tree.这允许人们找到他们想要的nested tag ,而无需重建树。


Here is one of the examples that they have used:这是他们使用的示例之一:

cost = ["$2000","$3000","$4000")
traveltime = ["3hrs", "8hrs", "15hrs"]
i = 0

for elm in root.findall("./country"):
    ET.SubElement(elm, "Holiday", attrib={"fight_cost": cost[i],
                                          "trip_duration": traveltime[i]})
    i += 1

This example also answers the question of How do you dynamically add data to XML?此示例还回答了如何将数据动态添加到 XML 的问题?

They have accomplished this by using a list outside of the loop and ieteration through it with i他们通过在循环之外使用列表并使用i迭代它来实现这一点

In essence, this example helps explain how to reference nested content without remaking the entire tree, as well as how to dynamically add data to xml trees.从本质上讲,此示例有助于解释如何在不重新制作整个树的情况下引用嵌套内容,以及如何向 xml 树动态添加数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM