I had to output RSS ver2 with Python, but I made a note because it was moss several times at that time.
Python has a high affinity with json, but XML seems awkward. I have some libraries as below, but I can't realize what I want to do.
lastUpdate
After all, I settled down by converting from a DOM object to XML.
#!/usr/bin/env python
# coding: utf-8
from xml.dom.minidom import parseString
xml_template = "<rss version=\"2.0\">\
<channel>\
<title>title</title>\
<link>link</link>\
<description>desctiption</description>\
<language>ja</language>\
</channel></rss>"
dom = parseString(xml_template)
#Get channel node
channel = dom.getElementsByTagName("channel")[0]
#Generate item node
item = dom.createElement('item')
#Add to channel node
channel.appendChild(item)
#Subnode generation
subnode = dom.createElement('subnode')
subnode.appendChild(dom.createTextNode("Japanese is also OK"))
#Set attribute and value in subnote
subnode_attr = dom.createAttribute('key')
subnode_attr.value = 'value'
subnode.setAttributeNode(subnode_attr)
#Add subnode node to item node
item.appendChild(subnode)
#Convert dom to xml and format
print (dom.toprettyxml())
output
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>title</title>
<link>link</link>
<description>desctiption</description>
<language>ja</language>
<item>
<subnode key="value">Japanese is also OK</subnode>
</item>
</channel>
</rss>
#!/usr/bin/env python
# coding: utf-8
import xml.dom.minidom
#Generating a DOM object
dom = xml.dom.minidom.Document()
#Creating and adding root nodes
root = dom.createElement('root')
dom.appendChild(root)
#Subnode generation
subnode = dom.createElement('subnode')
subnode.appendChild(dom.createTextNode("Japanese is also OK"))
#Set attribute and value in subnote
subnode_attr = dom.createAttribute('key')
subnode_attr.value = 'value'
subnode.setAttributeNode(subnode_attr)
#Add subnode node to item node
root.appendChild(subnode)
#Convert dom to xml and format
print (dom.toprettyxml())
output
<?xml version="1.0"?>
<root>
<subnode key="value">Japanese is also OK</subnode>
</root>
json best
Reference
Recommended Posts