0

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.

Mansoor Akram
  • 1,997
  • 4
  • 24
  • 40

1 Answers1

1

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..."}

syntonym
  • 7,134
  • 2
  • 32
  • 45
  • I am having one more issue: whenever i set "ET.SubElement(wp_author, "wp:author_last_name").text = "<![CDATA[]]>"" it returns me this: encoded result: "<![CDATA[]]>" – Mansoor Akram Jun 21 '16 at 12:51
  • How to decode these character before generating xml file. – Mansoor Akram Jun 21 '16 at 12:51
  • If I undertand you correctly you want to insert CDATA into your xml. [Here](http://stackoverflow.com/questions/174890/how-to-output-cdata-using-elementtree) is one question (with answers), but there are others. If they don't work for you it is best if you create a new question here in SO. – syntonym Jun 21 '16 at 12:54