【发布时间】:2016-06-21 18:26:13
【问题描述】:
问题背景:
我有一个 XML 文件,我正在将其导入 BeautifulSoup 并进行解析。一个节点具有以下内容:
<DIAttribute name="ObjectDesc" value="Line1
Line2
Line3"/>
请注意,该值在文本中具有 &#xD; 和 &#xA;。我知道这些是回车和换行的 XML 表示。
当我导入 BeautifulSoup 时,值会转换为以下内容:
<DIAttribute name="ObjectDesc" value="Line1
Line2
Line3"/>
您会注意到&#xd;&#xA; 被转换为换行符。
我的用例要求该值保持为原始值。知道如何让它留下来吗?还是转换回来?
源代码:
蟒蛇:(2.7.11)
from bs4 import BeautifulSoup #version 4.4.0
s = BeautifulSoup(open('test.xml'),'lxml-xml',from_encoding="ansi")
print s.DIAttribute
#XML file looks like
'''
<?xml version="1.0" encoding="UTF-8" ?>
<DIAttribute name="ObjectDesc" value="Line1
Line2
Line3"/>
'''
Notepad++ 说源 XML 文件的编码是 ANSI。
我尝试过的事情:
- 我浏览了文档但没有成功。
-
第 3 行的变化:
print s.DIAttribute.prettify('ascii') print s.DIAttribute.prettify('windows-1252') print s.DIAttribute.prettify('ansi') print s.DIAttribute.prettify('utf-8') print s.DIAttribute['value'].replace('\r','
').replace('\n','
') #This works, but it feels like a bandaid and will likely other problems will remain.
有什么想法吗?我感谢任何 cmets/建议。
【问题讨论】:
-
你可以在解析前用一些原始字符串替换它们,最后按原样处理。
标签: python xml encoding beautifulsoup