A. 1、使用python讀取依據生成的xml文件,添加樣式表,最中生成一個html文件
#coding=utf8
#引入要用到的xml解析庫這里我們用比較輕量級的minidom就行了
importxml.dom.minidom
#定義一個html輸出模板
#後面我們只是要把這段html中的學生數據部分(<student_trs/>)換成xml中讀到的數據
template="""
<html>
<tableborder="1"style="width:100%;text-align:center;">
<tr>
<tdcolspan="4">學生信息</td>
</tr>
<student_trs/>
</table>
</html>
"""
#讀取xml文檔內容,這里假設是a.xml
dom=xml.dom.minidom.parse('a.xml')
#獲取xml中的所有student節點
student_nodes=dom.getElementsByTagName('student')
#初始化student_trs為空
student_trs=""
#遍歷每一條學生信息
fornodeinstudent_nodes:
#getAttribute用戶獲取節點的屬性,得到id屬性值即學號
#因為xml解析後是Unicode編碼的,所以這里要轉成utf8編碼,下面同理
sid=node.getAttribute("id").encode('utf-8')
#獲取所有子節點
children=node.childNodes
forchildinchildren:
#判斷子節點的名字為姓名、性別、專業的話,就採集其對應文本
ifchild.nodeName.encode('utf-8')=="姓名":
#使用。childNodes[0].nodeValue的方法得到節點的文本
name=child.childNodes[0].nodeValue.encode('utf-8')
ifchild.nodeName.encode('utf-8')=="性別":
sex=child.childNodes[0].nodeValue.encode('utf-8')
ifchild.nodeName.encode('utf-8')=="專業":
specialty=child.childNodes[0].nodeValue.encode('utf-8')
#組成html中的一行學生數據
student_tr="<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>"%(sid,name,sex,specialty)
#將這一行數據添加到總數據中
student_trs+=student_tr
#替換模板的<student_trs/>為我們上面所得到的html數據
html=template.replace("<student_trs/>",student_trs)
#輸入html結果到output.html
open("output.html","w").write(html)
#PS:你提供的xml數據有問題,確實了一個</students>標記
#正確的xml應該如下
"""
<?xmlversion="1.0"encoding="UTF-8"?>
<person>
<students>
<studentid="20140711">
<姓名>三</姓名>
<性別>男</性別>
<專業>計算機</專業>
</student>
</students>
</person>
"""
B. python讀取xml文件報錯ValueError: multi-byte encodings are not supported
問題 在使用python對xml文件進行讀取時,提示ValueError: multi-byte encodings are not supported
xml是用gb2312編碼的。
很多貼子上說把xml的編碼格式改為utf-8,就可以正常執行了。
但是這里有一個問題,xml原先的編碼格式和encoding欄位顯示的編碼格式都是gb2312,如果只改了encoding欄位,之後再使用這個xml文件,就會按utf-8解析gb2312,會造成不可預知的後果。
第二個問題就是指改一個xml文件還好,但是有幾百上千的時候,改這個就不方便了。
解決方案 用parseString函數
python提供了兩種xml的輸入方式,一種是文件,一種是字元串。我們可以先將xml文件讀入內存,然後關閉文件。再將xml字元串中的gb2312用replace改為utf-8,然後用parseString解析,這樣就不會報錯。
注意事項 如果文件過大,有可能內存不夠,所以適用於小的xml文件。注意要把不使用的文件給close掉,以免佔用文件描述符。