我如何替换 ElementTree 中的子元素

发布于 2024-12-26 07:06:03 字数 71 浏览 2 评论 0原文

我想根据某些标准将子元素从一棵树替换到另一棵树。我可以使用理解来做到这一点吗?但是我们如何替换ElementTree中的元素呢?

I want to replace child elements from one tree to another , based on some criteria. I can do this using Comprehension ? But how do we replace element in ElementTree?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

白况 2025-01-02 07:06:03

您无法替换 ElementTree 中的元素,只能使用 Element

即使您调用 ElementTree.find(),它也只是 getroot().find() 的快捷方式。

因此,您确实需要:

  • 提取父元素
  • 在该父元素上使用理解(或您喜欢的任何内容)

如果您的目标是根子元素,则提取父元素会很容易(只需调用 getroot()< /code>)否则你将不得不找到它。

You can't replace an element from the ElementTree you can only work with Element.

Even when you call ElementTree.find() it's just a shortcut for getroot().find().

So you really need to:

  • extract the parent element
  • use comprehension (or whatever you like) on that parent element

The extraction of the parent element can be easy if your target is a root sub-element (just call getroot()) otherwise you'll have to find it.

拥抱我好吗 2025-01-02 07:06:03

与 DOM 不同,etree 没有显式的多文档功能。但是,您应该能够将元素从一个文档自由移动到另一个文档。您可能需要调用 _setroot这样做之后。

通过调用 insert 然后 remove,可以替换文档中的节点。

Unlike the DOM, etree has no explicit multi-document functions. However, you should be able to just move elements freely from one document to another. You may want to call _setroot after doing so.

By calling insert and then remove, you can replace a node in a document.

欲拥i 2025-01-02 07:06:03

我是Python新手,但我发现了一种狡猾的方法来做到这一点:

输入文件input1.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <import ref="input2.xml" />
    <name awesome="true">Chuck</name>
</root>

输入文件input2.xml

<?xml version="1.0" encoding="UTF-8"?>
<foo>
    <bar>blah blah</bar>
</foo>

Python代码:(注意,混乱和hacky)

import os
import xml.etree.ElementTree as ElementTree

def getElementTree(xmlFile):
    print "-- Processing file: '%s' in: '%s'" %(xmlFile, os.getcwd())
    xmlFH = open(xmlFile, 'r')
    xmlStr = xmlFH.read()
    et = ElementTree.fromstring(xmlStr)
    parent_map = dict((c, p) for p in et.getiterator() for c in p)
    # ref: https://stackoverflow.com/questions/2170610/access-elementtree-node-parent-node/2170994
    importList = et.findall('.//import[@ref]')
    for importPlaceholder in importList:
        old_dir = os.getcwd()
        new_dir = os.path.dirname(importPlaceholder.attrib['ref'])
        shallPushd = os.path.exists(new_dir)
        if shallPushd:
            print "  pushd: %s" %(new_dir)
            os.chdir(new_dir) # pushd (for relative linking)
        # Recursing to import element from file reference
        importedElement = getElementTree(os.path.basename(importPlaceholder.attrib['ref']))

        # element replacement
        parent = parent_map[importPlaceholder]
        index = parent._children.index(importPlaceholder)
        parent._children[index] = importedElement

        if shallPushd:
            print "  popd: %s" %(old_dir)
            os.chdir(old_dir) # popd

    return et

xmlET = getElementTree("input1.xml")
print ElementTree.tostring(xmlET)

给出输出:

-- Processing file: 'input1.xml' in: 'C:\temp\testing'
-- Processing file: 'input2.xml' in: 'C:\temp\testing'
<root>
    <foo>
    <bar>blah blah</bar>
</foo><name awesome="true">Chuck</name>
</root>

这是根据以下信息得出的结论:

I'm new to python, but I've found a dodgy way to do this:

Input file input1.xml:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <import ref="input2.xml" />
    <name awesome="true">Chuck</name>
</root>

Input file input2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<foo>
    <bar>blah blah</bar>
</foo>

Python code: (note, messy and hacky)

import os
import xml.etree.ElementTree as ElementTree

def getElementTree(xmlFile):
    print "-- Processing file: '%s' in: '%s'" %(xmlFile, os.getcwd())
    xmlFH = open(xmlFile, 'r')
    xmlStr = xmlFH.read()
    et = ElementTree.fromstring(xmlStr)
    parent_map = dict((c, p) for p in et.getiterator() for c in p)
    # ref: https://stackoverflow.com/questions/2170610/access-elementtree-node-parent-node/2170994
    importList = et.findall('.//import[@ref]')
    for importPlaceholder in importList:
        old_dir = os.getcwd()
        new_dir = os.path.dirname(importPlaceholder.attrib['ref'])
        shallPushd = os.path.exists(new_dir)
        if shallPushd:
            print "  pushd: %s" %(new_dir)
            os.chdir(new_dir) # pushd (for relative linking)
        # Recursing to import element from file reference
        importedElement = getElementTree(os.path.basename(importPlaceholder.attrib['ref']))

        # element replacement
        parent = parent_map[importPlaceholder]
        index = parent._children.index(importPlaceholder)
        parent._children[index] = importedElement

        if shallPushd:
            print "  popd: %s" %(old_dir)
            os.chdir(old_dir) # popd

    return et

xmlET = getElementTree("input1.xml")
print ElementTree.tostring(xmlET)

gives the output:

-- Processing file: 'input1.xml' in: 'C:\temp\testing'
-- Processing file: 'input2.xml' in: 'C:\temp\testing'
<root>
    <foo>
    <bar>blah blah</bar>
</foo><name awesome="true">Chuck</name>
</root>

this was concluded with information from:

絕版丫頭 2025-01-02 07:06:03

是的!使用切片语法,您可以通过理解来完成它。前任:

import xml.etree.ElementTree as etree

path = r'C:\Users\XXX\myfile.xml'
tree = etree.parse(path)
root = tree.getroot()


root[:] = [child for child in root if child.get('some-attribute') == 'something']
tree.write(f'{path}.filtered.xml')

Yes! Using the slice syntax you can do it with comprehension. Ex:

import xml.etree.ElementTree as etree

path = r'C:\Users\XXX\myfile.xml'
tree = etree.parse(path)
root = tree.getroot()


root[:] = [child for child in root if child.get('some-attribute') == 'something']
tree.write(f'{path}.filtered.xml')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文