python xml.dom.minidom.parse not well-formed error

用python解析xml,遇到以下error,

ParseError: not well-formed (invalid token): line 1, column 17
因为xml文件中有以下一段文字,

<news>
 <title>2016年1月2日 if(window.yzq_d==null)window.yzq_d=new Object();
window.yzq_d['vYTLAWRhZD8-']='&U=13jt854h2%2fN%3dvYTLAWRhZD8-%2fC%3d300908984.301767463.303376606.311556217%2fD%3dULT%2fB%3d302054045';</title>
</news>

其中的“&U” 破坏了xml的结构,

原来的代码是这样写的:

DOMTree = xml.dom.minidom.parse(file_path)
collection = DOMTree.documentElement
categoryNameStr = collection.getAttribute("name")

由于要过滤特殊字符,需要改成以下写法:

import codecs
def replace_special_character(content):
    content = content.replace("&U", "&U")
    return content
datasource = codecs.open(readFileAddress, 'r', 'UTF-8')
xml_str = ""
for line in datasource:
    xml_str += line
xml_str = replace_special_character(xml_str)
DOMTree = xml.dom.minidom.parseString(xml_str)
collection = DOMTree.documentElement
categoryNameStr = collection.getAttribute("name")


如果有更好的方法,欢迎提出。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值