3
问题背景 :
我有我导入到BeautifulSoup和通过解析XML文件。一个节点有以下几点:处理``在Python
<DIAttribute name="ObjectDesc" value="Line1
Line2
Line3"/>
注意,此数值
和文本中

。我知道这些是回车和换行符的XML表示。
当我导入BeautifulSoup,价值被转换成如下:
<DIAttribute name="ObjectDesc" value="Line1
Line2
Line3"/>
你会发现

被转换成一个换行符。
我的用例要求值保持原来的值。任何想法如何让它留下来?还是将其转换回来?
源码:
蟒:(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"/>
'''
记事本++表示源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.
任何想法吗?我很欣赏任何意见/建议。
你可以在解析之前用一些原始字符串替换它们,最后按照它应该的那样对待它们。 – josifoski