XML檔案result.xml,內容如下:
<ccm>
<metric>
<complexity>1</complexity>
<unit>multiply</unit>
<classification>A</classification>
<file>allmymath.py</file>
<startLineNumber>9</startLineNumber>
<endLineNumber>10</endLineNumber>
</metric>
<metric>
<complexity>1</complexity>
<unit>divide</unit>
<classification>A</classification>
<file>allmymath.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)
利用Jinja2生成HTML
模版檔案templa/base.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>
渲染指令碼:
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)