从xml中删除元素并写入文件 - Python - lxml

时间:2017-04-19 14:44:58

标签: python lxml

我正在学习使用Python中的xml,而且我被卡住了。 我需要从文件中读取一个xml,以释放一个元素(属性id = 1)并重写没有被删除元素的xml ...这是代码:

from lxml import etree as le

file = open("default.xml", 'r')
        tree = le.parse(file)
        file.close()
        for cams in tree.xpath("//camera[@id=\'1\']"):
            cams.getparent().remove(cams)
        file = open("default.xml", 'w')
        #tree = le.tostring(tree, pretty_print=True, xml_declaration=True)
        file.write(le.tostring(tree, pretty_print=True, xml_declaration=True))
        file.close()

我收到此错误:TypeError:write()参数必须是str,而不是bytes

这是xml文件:

<?xml version="1.0" ?><settings>
    <modifica>0</modifica>
    <source>0</source>
    <soglie>
        <diffPerson>19</diffPerson>     
    </soglie>
    <size>
        <onePerson>4</onePerson>
        <twoPersons>7</twoPersons>
        <blobSize>10</blobSize>
        <dimBordoBlob>0</dimBordoBlob>
    </size>
    <invertX>0</invertX>
    <invertY>0</invertY>
    <feedback>1</feedback>
    <camere>
        <camera id="1">
            <larghezza>55</larghezza>
            <altezza>100</altezza>
            <ip>192.168.2.226</ip>
            <posizione>1</posizione>
            <offsetX>0</offsetX>
            <offsetY>22</offsetY>
            <port>5601</port>
        </camera>
    <camera id="2">
        <larghezza>55</larghezza>
        <altezza>100</altezza>
        <ip>192.168.2.226</ip>
        <posizione>0</posizione>
        <offsetX>45</offsetX>
        <offsetY>0</offsetY>
        <port>5600</port>
    </camera>
</camere>
    <room>
        <tipo>1</tipo>
        <larghezzaCm>4000</larghezzaCm>
        <altezzaCm>1500</altezzaCm>
    </room>
    <udpOut>
        <ip>192.168.2.253</ip>
        <port>3030</port>
    </udpOut>
    <udpIn>
        <ip>192.168.2.245</ip>
        <port>5050</port>
    </udpIn>
    <settings>
        <life>10</life>
    </settings>
    <master>1</master>
    <masterIP>192.168.2.245</masterIP>
</settings>

1 个答案:

答案 0 :(得分:0)

很抱歉时间损失。

解决方案是设置

file = open("default.xml", 'wb')

而不是:

file = open("default.xml", 'w')