在写xml之前,我在xml和python上存在删除节点的问题。
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
import xml.etree.ElementTree as etree
root = Element('p:FatturaElettronica')
Header = SubElement(root, 'FatturaElettronicaHeader')
CedentePrestatore = SubElement(Header, 'CedentePrestatore')
在写入磁盘之前,我想删除“ CedentePrestatore”子元素,我尝试:
xv = root.findall('.//CedentePrestatore')
root.remove(xv) <------------------ ERROR
为什么?在将更改写入磁盘之前,如何删除节点?
完整代码:
#!/usr/bin/env python
# -*- coding: cp1252 -*-
#import xlsxwriter
import sys
import os
import datetime
import re
import logging
import ConfigParser
import shutil
#import MySQLdb as mdb
import smtplib
#import xlrd as opx
# xlwt as opw
import unicodedata
import base64
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
import xml.etree.ElementTree as etree
def test():
etree.register_namespace('ds',"http://www.w3.org/2000/09/xmldsig#") #some name
etree.register_namespace('p',"http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2") #some name
etree.register_namespace('xsi',"http://www.w3.org/2001/XMLSchema-instance") #some name
root = Element('p:FatturaElettronica')
print "ok"
root = Element('p:FatturaElettronica')
Header = SubElement(root, 'FatturaElettronicaHeader')
DatiTr = SubElement(Header, 'DatiTrasmissione')
IdTra = SubElement(DatiTr, 'IdTrasmittente')
IdPaese = SubElement(IdTra, 'IdPaese')
IdCodice = SubElement(IdTra, 'IdCodice')
IdCodice.text = '0000000'
IdPaese.text = 'IT'
ProgressivoInvio = SubElement(DatiTr, 'ProgressivoInvio')
ProgressivoInvio.text = '1'
FormatoTrasmissione = SubElement(DatiTr, 'FormatoTrasmissione')
FormatoTrasmissione.text = 'FPR12'
xc = root.find('.//ProgressivoInvio')
root.remove(xc)
if __name__ == '__main__':
reload(sys)
sys.setdefaultencoding('cp1252')
test()