2012-08-28 125 views
12

我正在編寫一個腳本,它用BeautifulStoneSoup編輯XML文件,但該庫將所有標記轉換爲小寫。有沒有辦法保存案件?如何在BeautifulSoup.BeautifulStoneSoup中維護區分大小寫的標籤?

import BeautifulSoup  
xml = "<TestTag>a string</TestTag>"  
soup = BeautifulSoup.BeautifulStoneSoup(xml, markupMassage=False)  
print soup.prettify() # or soup.renderContents() 
#prints 
>>> <testtag>a string</testtag> 
#instead of the expected 
>>> <TestTag>a string</TestTag> 

回答

15

你可以使用Beautiful Soup 4,如下(需要lxml的XML庫):

In [10]: from bs4 import BeautifulSoup 

In [11]: xml = "<TestTag>a string</TestTag>" 

In [12]: soup = BeautifulSoup(xml, "xml") 

In [13]: print soup 
<?xml version="1.0" encoding="utf-8"?> 
<TestTag>a string</TestTag> 

In [14]: 
+1

感謝,取得了升級,它的偉大工程。對於未來的讀者:運行'pip安裝BeautifulSoup4'不是'pip安裝beautifulsoup --upgrade' – TankorSmash

+1

值得一提的是它需要'xml'庫,而不是'lxml',這是美麗的建議,如果你運行它沒有規範是什麼。 'lxml'不維護大小寫。 –

+0

@KeithSmiley:是的,當使用'soup = BeautifulSoup(xml,「lxml」)'時,使用lxml的HTML解析器。請參閱http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser。 – mzjn