0

サンプルデータです。

入力.xml

<root>
    <entry id="1">
    <headword>go</headword>
    <example>I <hw>go</hw> to school.</example>
</entry>
</root>

ノードとその子孫を に入れたいと思います。あれは、

output.xml

<root>
    <entry id="1">
    <headword>go</headword>
            <examplegrp>
                <example>I <hw>go</hw> to school.</example>
            </examplegrp>
</entry>
</root>

私の貧弱で不完全なスクリプトは次のとおりです。

import codecs
import xml.etree.ElementTree as ET

fin = codecs.open(r'input.xml', 'rb', encoding='utf-8')

data = ET.parse(fin)
root = data.getroot()

example = root.find('.//example')
for elem in example.iter():
    ---and then I don't know what to do---
4

2 に答える 2

0

http://docs.python.org/3/library/xml.dom.html?highlight=xml#node-objects http://docs.python.org/3/library/xml.dom.html?highlight=xml #ドキュメント オブジェクト

ドキュメント要素を作成し、それにリーチ結果を追加するパラダイムに従うことをお勧めします。

group = Document.createElement(tagName)
for found in founds:
    group.appendNode(found)

または、このようなもの

于 2013-01-29T12:06:30.957 に答える
0

これを行う方法の例を次に示します。

text = """
<root>
    <entry id="1">
        <headword>go</headword>
        <example>I <hw>go</hw> to school.</example>
    </entry>
</root>
"""

import lxml.etree
import StringIO

data = lxml.etree.parse(StringIO.StringIO(text))
root = data.getroot()

for entry in root.xpath('//example/ancestor::entry[1]'):
    examplegrp = lxml.etree.SubElement(entry,"examplegrp")
    nodes = [node for node in entry.xpath('./example')]
    for node in nodes:
        entry.remove(node)
        examplegrp.append(node)

print lxml.etree.tostring(root,pretty_print=True)

出力は次のとおりです。

<root>
    <entry id="1">
        <headword>go</headword>
        <examplegrp><example>I <hw>go</hw> to school.</example>
    </examplegrp></entry>
</root>
于 2013-01-29T12:10:54.887 に答える