简体   繁体   English

使用python元素树将节点插入XML

[英]Inserting nodes into XML using python element tree

I have the following XML structure and I want to add a new node if it does not exist at a specific location. 我有以下XML结构,如果在某个特定位置不存在,我想添加一个新节点。

<root>
    <OuterLevel>
        <Node>
            <Name>NodeA</Name>
        </Node>
        <Node>
            <Name>NodeB</Name>
        <Node>
        <SpecialNode>
            <Name>NodeZ</Name>
        </SpecialNode>
    </OuterLevel>
 </root>

I wrote a python script using element tree. 我用元素树写了一个python脚本。 http://docs.python.org/library/xml.etree.elementtree.html http://docs.python.org/library/xml.etree.elementtree.html

import xml.etree.ElementTree as ET
tree = ET.parse('sampleFile.xml')
root = tree.getroot()
newNodeStr = 'NewNode'

if root[0][0].tag != newNodeStr :
    print('Now we add it')
    newNode = ET.Element(newNodeStr)
    newNodeName = ET.Element('Name')
    newNodeName.text = 'NodeC'
    newNode.append(newNodeName)
    root[0].insert(0, newNode)

tree.write('sampleFileNew.xml')

I wanted the XML structure to look like this: 我希望XML结构看起来像这样:

<root>
    <OuterLevel>
        <NewNode>
            <Name>NodeC</Name>
        </NewNode>
        <Node>
            <Name>NodeA</Name>
        </Node>
        <Node>
            <Name>NodeB</Name>
        <Node>
        <SpecialNode>
            <Name>NodeZ</Name>
        </SpecialNode>
    </OuterLevel>
 </root>

But instead, it looks like this: 但相反,它看起来像这样:

<root>
    <OuterLevel>
        <NewNode><Name>NodeC</Name></NewNode><Node>
            <Name>NodeA</Name>
        </Node>
        <Node>
            <Name>NodeB</Name>
        <Node>
        <SpecialNode>
            <Name>NodeZ</Name>
        </SpecialNode>
    </OuterLevel>
 </root>

I used the insert() method from element tree because I thought it would give me what I needed, which is inserting a node at a specific location. 我使用了元素树中的insert()方法,因为我认为它会给我我需要的东西,即在特定位置插入一个节点。 However, it looks like the insert() doesn't actually care about what is already in that position in the tree structure. 但是,看起来insert()实际上并不关心树结构中该位置的内容。 Is there a method that I can use to fix the ordering? 有没有一种方法可以用来修复排序? Is there a better way of doing this? 有没有更好的方法呢?

从语法上讲,这两个输出是相同的,如果你保存文件然后重新解析它,tree.write()可能会按照你想要的方式打印你的输出,虽然我不确定。

Try this one it will pretty print the output as you want. 试试这个,它会很好地打印出你想要的输出。

    try:
        reparsed = mini.parseString(mini.parse('YOUR_FILE_NAME').toxml())
        pretty_string =  '\n'.join([line for line in reparsed.toprettyxml(indent=' '*4).split('\n') if line.strip()])

        f = open('YOUR_FILE_NAME', 'w') 
        f.write(pretty_string) 
    finally:
        f.close()

It looks like you may need to use the pretty_print = True when you're rewriting the tree to the file. 当您将树重写到文件时,您可能需要使用pretty_print = True。 Perhaps you're parsing it in it's previous pretty_print form but the insert() does not add your new node in pretty_print form. 也许您正在使用之前的pretty_print格式解析它,但insert()不会以pretty_print格式添加新节点。

If you're not using LXML i'm not sure if this is possible, but try just changing the print to: 如果您没有使用LXML,我不确定这是否可行,但只需将打印更改为:

tree.write('sampleFileNew.xml', pretty_print = True) tree.write('sampleFileNew.xml',pretty_print = True)

Again, you may need to import lxml to use this functionality. 同样,您可能需要导入lxml才能使用此功能。 Hope this helps. 希望这可以帮助。

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

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