【问题标题】:How to save data in xml如何在xml中保存数据
【发布时间】:2019-12-17 18:44:56
【问题描述】:

我想以这种格式将数据保存在xml中

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

我试过这个,但我不知道如何以上述格式保存:

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")

【问题讨论】:

  • 你能分享输入数据的样子吗?
  • 其实我是从网上报废的,想保存在 xml 中。
  • 您的代码至少有几个缩进错误 - 请修复。显示你得到的输出。将您的代码设为minimal reproducible example - 目前由于识别问题,我无法复制/粘贴并运行它以获得任何输出。

标签: python xml dataset


【解决方案1】:

docs for SubElement 说它有以下参数:parent, tag, attrib={}, **extra

您省略了tag,因此您的代码会出现错误TypeError: SubElement() takes at least 2 arguments (1 given)。你需要这样的东西:

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")

输出:&lt;posts&gt;&lt;row baz="qux" foo="bar" /&gt;&lt;/posts&gt;

【讨论】:

  • 哇完美!它可以按我的意愿完美运行,但只打印一行。我想打印多行。我的意思是如果有 20 行要打印,它会写 20 .. 我在循环中添加它
  • 如果您在讨论 XML 文件的格式,有很多选项:stackoverflow.com/questions/17402323/…
猜你喜欢
  • 1970-01-01
  • 2010-09-16
  • 2020-08-25
  • 1970-01-01
  • 2020-06-10
  • 1970-01-01
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多