0

I have these code where i found online.

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)

As you can see this function will auto open a file name record.html and it will write the num range (33 to 48) symb + num into this record.html file so after that i can view it as html. So now i want to combine this code with my other code which is

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)

What i want is how can i combine these two code and the function will auto create a file name "record.html" and inside this file, it will auto write the XML content of the restaurant name and address of all restaurants inside this record.html file? This is my xml code

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

1 Answer 1

1

Sure you can.

It's best to separate the concerns:

  • read_restaurants reads the XML file and yields dicts of restaurant names and addresses
  • generate_record_html calls that and writes the HTML accordingly.
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()
Sign up to request clarification or add additional context in comments.

4 Comments

Hi thanks for reply but i think there might be some problem when i run your code, i am using python and visual studio code to run. Traceback (most recent call last): File "d:/python file/test2.py", line 30, in <module> write_record_html() File "d:/python file/test2.py", line 18, in write_record_html for restaurant in read_restaurants(): File "d:/python file/test2.py", line 5, in read_restaurants root_node = ET.parse("scratch_1.xml").getroot()
Sorry – my test file was called scratch_1.xml. Change that to record.xml in the code.
Sorry actually i have another question but can you also help me about this, the output was fine but i have another same question like "display the XML content of the restaurant name and capacity for a rate larger than 4 in HTML file."
Well, picking up from this, you'd probably also parse the capacity subtag's content into the restaurant dict in the read_restaurants() function, then have a suitable if statement in the write function to skip restaurants with capacity less than four.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.