首页 > 解决方案 > 使用python代码运行xml并保存为html文件

问题描述

我在网上找到了这些代码。

strTable = "<html><table><tr><th>Address</th><th>Name</th></tr>"
 
for num in range(33,48):
 symb = chr(num)
 strRW = "<tr><td>"+str(symb)+ "</td><td>"+str(num)+"</td></tr>"
 strTable = strTable+strRW
 
strTable = strTable+"</table></html>"
 
hs = open("record.html", 'w')
hs.write(strTable)
 
print (strTable)

如您所见,此函数将自动打开一个文件名 record.html,并将 num 范围(33 到 48)symb + num 写入此 record.html 文件,因此之后我可以将其视为 html。所以现在我想将此代码与我的其他代码结合起来

import xml.etree.ElementTree as ET

root_node = ET.parse('record.xml').getroot()

for tag in root_node.findall('restaurant'):
        value = tag.attrib['name']
        print("Restaurant name:")
        print(value)
        for capacity in tag.findall('address'):
            print("Address:")
            print(address.text)

我想要的是如何结合这两个代码,该函数将自动创建一个文件名“record.html”,在这个文件中,它会自动在这个记录中写入餐厅名称和所有餐厅地址的 XML 内容。 .html 文件?这是我的 xml 代码

<?xml version="1.0" encoding="UTF-8"?> 
<record>
   <restaurant name="La Pasteria" rate="1">
      <cuisine id="-">Italian</cuisine>
      <address>8, Jalan Mata Kuching, 89200 Selangor</address>
      <capacity>300</capacity>
      <phone>06-2899808</phone>
      <phone>06-2829818</phone>
         <general>-</general>
         <shop1>-</shop1>
         <shop2>-</shop2>
   </restaurant>
   <restaurant name="Nyonya Baba" rate="2">
      <cuisine id="112">Malaysian</cuisine>
      <address>21, Jalan Taming Sari, 75350 Melaka</address>
      <address>25, Jalan Bukit Beruang, 75450 Melaka</address>
      <capacity>80</capacity>
      <phone>
      <general>012-2677498</general>
         <shop1>06-2855413</shop1>
         <shop2>06-2856418</shop2>
      </phone>
   </restaurant>
</record>

标签: pythonhtmlxml

解决方案


你当然可以。

最好将关注点分开:

  • read_restaurants读取 XML 文件并生成餐厅名称和地址的字典
  • generate_record_html调用它并相应地编写 HTML。
import xml.etree.ElementTree as ET


def read_restaurants():
    root_node = ET.parse("record.xml").getroot()

    for tag in root_node.findall("restaurant"):
        value = tag.attrib["name"]
        restaurant = {"name": value, "addresses": []}
        for address in tag.findall("address"):
            restaurant["addresses"].append(address.text)
        yield restaurant


def write_record_html():
    with open("record.html", "w") as f:
        f.write("<html><table><tr><th>Name</th><th>Address</th></tr>")
        for restaurant in read_restaurants():
            for address in restaurant["addresses"]:
                f.write(
                    "<tr><td>"
                    + restaurant["name"]
                    + "</td><td>"
                    + address
                    + "</td></tr>\n"
                )
        f.write("</table></html>")


write_record_html()

推荐阅读