- 论坛徽章:
- 0
|
我对python语言一窍不通,从一个同事那里要了一段代码,主要功能就是将GB2312格式的一个xml文件转换成UTF-8格式,但是我怎么运行xml的格式都没有变化,求教各位大侠解释一下这段代码:
# -*- encoding: gb2312 -*-
import os.path
import string
import optparse
#import ConfigParser
import os
import re
import codecs
from xml.dom.minidom import *
def main():
p = optparse.OptionParser()
#-s后面的参数是测试结果源文件
p.add_option("-s",dest="TestResultFile")
#-d后面的参数是统计后输出的目标文件
p.add_option("-d",dest="DestOutPutFile")
(options, arguments) = p.parse_args()
#调试打桩
#options.TestResultFile = "e:\TestResult.xml"
#options.DestOutPutFile = "e:\TestResultStatic.xml"
#将GB2312格式转为UTF-8格式
f = codecs.open(options.TestResultFile, "rb", "gb2312")
text = f.read().encode("utf-8")
f.close
f = open(options.TestResultFile, "wb")
f.write(text)
f.close()
#print text.decode(‘utf-8′).encode(‘gb2312′)
try:
#print "!!!!!Try"
doc= xml.dom.minidom.parse(options.TestResultFile)
except:
#print "!!!!!Except"
doc= xml.dom.minidom.parse("D:\TestResult.xml")
#取出所有的TestCase
TestCase = doc.getElementsByTagName("TestCase")
countPassCase = 0
countFailCase = 0
for i in range(len(TestCase)):
flagTestResult = TestCase.getElementsByTagName("Result")
if (getText(flagTestResult[0].childNodes) == "Pass"):
countPassCase = countPassCase + 1
if (getText(flagTestResult[0].childNodes) == "Fail"):
countFailCase = countFailCase + 1
#创建输出文件对象
implementation = xml.dom.minidom.DOMImplementation()
document = implementation.createDocument(None,"CI",None)
fileOuptutXML = document.documentElement
#创建新的统计标签
flagTotalCase = document.createElement("TOTAL")
flagPassCase = document.createElement("PASS")
flagFailCase = document.createElement("FAIL")
flagTestDetail= document.createElement("DETAIL")
textTotalCase = document.createTextNode(repr(len(TestCase)))
textPassCase = document.createTextNode(repr(countPassCase))
textFailCase = document.createTextNode(repr(countFailCase))
flagTotalCase.appendChild(textTotalCase)
flagPassCase.appendChild(textPassCase)
flagFailCase.appendChild(textFailCase)
for j in range(len(TestCase)):
flagTestDetail.appendChild(TestCase[j])
fileOuptutXML.appendChild(flagTotalCase)
fileOuptutXML.appendChild(flagPassCase)
fileOuptutXML.appendChild(flagFailCase)
fileOuptutXML.appendChild(flagTestDetail)
out=file(options.DestOutPutFile, 'w')
writer = codecs.lookup('utf-8')[3](out)
#doc.writexml(writer,indent="",addindent=" ",newl="\n",encoding='utf-8')
document.writexml(writer,encoding='utf-8')
#print "Write to file:"+options.DestOutPutFile
def getText(nodelist):
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
#node.normalize()
for i in range(len(node.data)):
if not (node.data == '\n' or node.data == ' '):
rc = rc + node.data
return rc
#main()
xml文件:<?xml version="1.0" ?>
<CI>
<TestCase><Name><![CDATA[半速率正常测量报告不功控时BCCH_CBCH测试]]></Name><Result>Fail</Result><TestCaseTime>2009-10-22 19:01:40:392</TestCaseTime></TestCase>
</CI> |
|