Python 解析 XML 文件生成 HTML

XML文件result.xml,内容如下:

<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)

利用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)

参考:

posted @ 2019-03-03 21:33  Michael翔  阅读(2228)  评论(0编辑  收藏  举报