XML文件result.xml,內容以下:css
<ccm> <metric> <complexity>1</complexity> <unit>multiply</unit> <classification>A</classification> <file>all\mymath.py</file> <startLineNumber>9</startLineNumber> <endLineNumber>10</endLineNumber> </metric> <metric> <complexity>1</complexity> <unit>divide</unit> <classification>A</classification> <file>all\mymath.py</file> <startLineNumber>13</startLineNumber> <endLineNumber>14</endLineNumber> </metric> </ccm>
import xml.etree.cElementTree as ET import os import sys tree = ET.ElementTree(file='result.xml') # 根元素(root)是一個Element對象。咱們看看根元素都有哪些屬性 root = tree.getroot() # 沒錯,根元素並無屬性。與其餘Element對象同樣,根元素也具有遍歷其直接子元素的接口 for child_of_root in root: print(child_of_root,child_of_root.attrib) for x in child_of_root: print(child_of_root, x, x.tag,':',x.text)
模版文件templa/base.html
:html
<!DOCTYPE html> <html lang="en"> <head> <title>Radon</title> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <h1>Radon-圈複雜度檢查結果</h1> <table class="table table-hover"> <thead> <tr> {% for td in data[0] %} <th>{{ td.tag }}</th> {% endfor %} </tr> </thead> <tbody> {%for m in data%} {% set complexity = m[0].text|float %} {% if m[0].text|float < 6 %} #或者 {% if complexity < 6 %} <tr class="success"> {% for v in m %} <td>{{v.text}}</td> {% endfor %} </tr> {% else %} <tr class="danger"> {% for v in m %} <td>{{v.text}}</td> {% endfor %} </tr> {% endif %} {%endfor%} </tbody> </table> </body> </html>
渲染腳本:python
from jinja2 import Environment, FileSystemLoader t=[] for metric in root: t.append(metric) print(t) xml_loader = FileSystemLoader("template") xml_env = Environment(loader=xml_loader) xml_tmp = xml_env.get_template("base.html") xml_info = xml_tmp.render(data=t) with open(os.path.join("template", "result.html"), "w") as f: f.write(xml_info)