python - 删除 xml 文件的第一部分,无法序列化
问题描述
我有一个 xml 文件,它的开头如下:
'''some non ascii character'''
<b:FatturaElettronica xmlns:b="#">
<FatturaElettronicaHeader>
<DatiTrasmissione>
<IdTrasmittente>
<IdPaese>IT</IdPaese>
我需要全部删除,直到
<FatturaElettronicaHeader>
现在代码是:
import xml.etree.ElementTree as ET
import xml.etree.ElementTree as ETree
from lxml import etree
parser = etree.XMLParser(encoding='utf-8', recover=True, remove_comments=True, resolve_entities=False)
tree = ETree.parse('test.xml', parser)
root = tree.getroot()
print etree.tostring(root)
给我:
Traceback (most recent call last):
File "xml2.py", line 14, in <module>
print etree.tostring(root)
File "src/lxml/etree.pyx", line 3350, in lxml.etree.tostring
TypeError: Type 'NoneType' cannot be serialized.
没有它工作的 xml 文件的第一部分。
泰
解决方案
您可以使用find()函数来搜索第一个括号。
import xml.etree.ElementTree as ET
with open ('...XMLFILE.xml', 'r') as file:
filestring = file.read()
XML_start = filestring.find('<')
print(XML_start) #gives 31
tree = ET.fromstring(filestring[XML_start:])
for i in tree.iter():
print(i.tag) #gives {#}FatturaElettronica, FatturaElettronicaHeader, ...
而且您的 xml 文件也必须正确:
'''some non ascii character'''
<b:FatturaElettronica xmlns:b="#">
<FatturaElettronicaHeader>
<DatiTrasmissione>
<IdTrasmittente>
<IdPaese>IT</IdPaese>
</IdTrasmittente>
</DatiTrasmissione>
</FatturaElettronicaHeader>
</b:FatturaElettronica>
推荐阅读
- angular - 在 require.context() 中使用模块路径时在 afterAll [object ErrorEvent] 中引发错误
- java - 如何只在字符串中保留不同类型的字母,例如:拉丁字母、片假名、西里尔字母
- c# - 如何避免实体框架与空/空数据库的连接
- javascript - 线程以代码 0 结束 - FileSystemWatcher?
- javascript - 为什么我的代码没有在 Alexa 开发控制台模拟器上运行 if 语句,即使我说出/键入插槽中存在的值?
- asp.net - Web.config 发布转换未作为 Azure DevOps 服务器中 Web 应用程序构建的一部分应用
- mysql - 在mysql中添加查询的时间范围
- windows - Windows Batch - 尝试通过 blat.exe 发送邮件时出错
- php - 使用条码机时如何停止自动提交
- java - Project Reactor:多个发布者发出 HTTP 调用,一个订阅者处理所有结果