Mansoor Akram
Mansoor Akram

Reputation: 2056

Create XML file with python?

Here is my code:

import xml.etree.ElementTree as ET

root = ET.Element("rss", version="2.0", xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/", xmlns:content="http://purl.org/rss/1.0/modules/content/", xmlns:wfw="http://wellformedweb.org/CommentAPI/", xmlns:dc="http://purl.org/dc/elements/1.1/", xmlns:wp="http://wordpress.org/export/1.2/")

ET.dump(root)

This is xml file i am trying to create:

<rss version="2.0"
    xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:wp="http://wordpress.org/export/1.2/"
>

this is very basic part of actual xml file but i am unable to correctly create it with elementtree. Until version number it works correctly but when i add "xmlns:something" it does not work. I am very new to xml so i have no idea even google is not able to help me understand.

NOTE: Please do tell me if lxml is more easy or this ElementTree. Because I have previously used lxml for xpath and css elements.

Upvotes: 0

Views: 604

Answers (1)

syntonym
syntonym

Reputation: 7384

Python identifiers are not allowed to have colons inside. ElementTree allows to pass an attribute dictionary by the key attrib:

ET.element("rss", attrib={"xmlns:excerpt":"http..."}

Upvotes: 1

Related Questions