2

谁能告诉我如何使用 python 附加 xml 文件

这是我的 file1.xml

<?xml version="1.0"?>
<addressbook>
    <person>
        <name>Eric Idle</name>
        <phone type='fix'>999-999-999</phone>
        <phone type='mobile'>555-555-555</phone>
        <address>
            <street>12, spam road</street>
            <city>London</city>
            <zip>H4B 1X3</zip>
        </address>
    </person>
</addressbook>

我想将它附加到另一个 xml 文件

<?xml version="1.0"?>

 <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
 </note>

有什么模块可以为我做到这一点...

我需要的输出是:

<addressbook>
    <person>
        <name>Eric Idle</name>
        <phone type='fix'>999-999-999</phone>
        <phone type='mobile'>555-555-555</phone>
        <address>
            <street>12, spam road</street>
            <city>London</city>
            <zip>H4B 1X3</zip>
        </address>
    </person>
    <note>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
     </note>
</addressbook>

现在我需要从文件中读取 xml,但后来我需要从服务器获取 xml 响应并将其转换为一个 xml 文件。所以请如果有人知道它会对我有很大帮助......

4

1 回答 1

5

编辑:由于问题发生了很大变化,因此删除了旧答案。

使用 lxml:

addressbook_xml = """<?xml version="1.0"?>
<addressbook>
    <person>
        <name>Eric Idle</name>
        <phone type='fix'>999-999-999</phone>
        <phone type='mobile'>555-555-555</phone>
        <address>
            <street>12, spam road</street>
            <city>London</city>
            <zip>H4B 1X3</zip>
        </address>
    </person>
</addressbook>"""

note_xml = """<?xml version="1.0"?>

 <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
 </note>
"""

from lxml import etree

# XML strings to etree
addressbook_root = etree.fromstring(addressbook_xml)
note_root = etree.fromstring(note_xml)

# append the note
addressbook_root.append(note_root)

# print the new addressbook XML document
print etree.tostring(addressbook_root)
于 2012-10-04T15:11:17.527 回答