2016-03-08 68 views
3

问题背景 :

我有我导入到BeautifulSoup和通过解析XML文件。一个节点有以下几点:处理``在Python

<DIAttribute name="ObjectDesc" value="Line1&#xD;&#xA;Line2&#xD;&#xA;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&#xD;&#xA;Line2&#xD;&#xA;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','&#xD;').replace('\n','&#xA;') #This works, but it feels like a bandaid and will likely other problems will remain. 
    

任何想法吗?我很欣赏任何意见/建议。

+0

你可以在解析之前用一些原始字符串替换它们,最后按照它应该的那样对待它们。 – josifoski

回答

1

只是为了记录,第一库,切勿妥善处理&#xa;实体:BeautifulSoup(data ,convertEntities=BeautifulSoup.HTML_ENTITIES)lxml.html.soupparser.unescapexml.sax.saxutils.unescape

这是什么工作(在Python 2.x中):

import sys 
import HTMLParser 

## accept file name as argument, or read stdin if nothing passed 
data = len(sys.argv) > 1 and open(sys.argv[1]).read() or sys.stdin.read() 

parser = HTMLParser.HTMLParser() 
print parser.unescape(data)