-1

I want to save data in xml in this format

<posts>
    <row Id="1" PostTypeId="1" AcceptedAnswerId="13" 
         CreationDate="2010-09-13T19:16:26.763" Score="297" ViewCount="472045" 
         Body="&lt;p&gt;This is a common question by those who have just rooted their phones.  What apps, ROMs, benefits, etc. do I get from rooting?  What should I be doing now?&lt;/p&gt;&#xA;" 
         OwnerUserId="10" 
         LastEditorUserId="16575" LastEditDate="2013-04-05T15:50:48.133" 
         LastActivityDate="2018-05-19T19:51:11.530" 
         Title="I've rooted my phone.  Now what?  What do I gain from rooting?" 
         Tags="&lt;rooting&gt;&lt;root-access&gt;" 
         AnswerCount="3" CommentCount="0" FavoriteCount="194" 
         CommunityOwnedDate="2011-01-25T08:44:10.820" />
</posts>

I tried this, but I don't know how will I save in the above format:

import xml.etree.cElementTree as ET
root = ET.Element("posts")
row = ET.SubElement(root, "row")

ET.SubElement(row, questionText = "questionText").text = questionText
            ET.SubElement(row, votes = "votes").text = votes
            ET.SubElement(row, tags = "tags").text = tags

tree = ET.ElementTree(root)
            tree.write("data.xml")
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
waseem
  • 116
  • 1
  • 13

1 Answers1

0

The docs for SubElement say it has the following arguments: parent, tag, attrib={}, **extra.

You omit the tag, so you get an error TypeError: SubElement() takes at least 2 arguments (1 given) with your code. You need something like:

import xml.etree.cElementTree as ET
root = ET.Element("posts")
row = ET.SubElement(root, "row", attrib={"foo":"bar", "baz":"qux"})

tree = ET.ElementTree(root)
tree.write("data.xml")

Outputs: <posts><row baz="qux" foo="bar" /></posts>

Nickolay
  • 31,095
  • 13
  • 107
  • 185
  • wow perfect! it works perfect as i wanted but it only prints one line. I want to print multiple lines. i mean if there are 20 lines to print it writes 20.. i added it in loop – waseem Aug 11 '19 at 07:31
  • If you're talking about the formatting of the XML file, there a re a number of options: https://stackoverflow.com/questions/17402323/use-xml-etree-elementtree-to-print-nicely-formatted-xml-files – Nickolay Aug 11 '19 at 07:41