我知道这个主题之前已经发布过,但即使之前所有关于它的帖子我似乎也无法弄清楚如何去做。
因此,在我的代码中,我正在创建并用一些东西填充一个 xml 文件。代码返回到文件创建和关闭后的 xml 代码,以编写更多内容。问题是,无论我使用哪种流/xml 读取器/写入器组合,文本中某些地方的缩进都会变得很奇怪。
这是代码:
XmlDocument xml = new XmlDocument();
xml.PreserveWhitespace = true;
XmlElement root = null;
FileStream fs = null;
if (File.Exists(fileName))
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
xml.Load(fs);
if (xml.GetElementsByTagName("anndata").Count > 0)
root = (XmlElement)xml.GetElementsByTagName("anndata").Item(0);
}
else
{
fs = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite);
root = xml.CreateElement("anndata");
xml.AppendChild(root);
}
//some writing to the xml doc.
fs.SetLength(0);
xml.Save(fs);
fs.Close();
现在一切都在 xml 文件中的一行中,我希望有一些缩进,所以有什么提示吗?
编辑:
我将最后一点更改为:
fs.SetLength(0);
XmlTextWriter writer = new XmlTextWriter(fs, Encoding.Unicode);
writer.Formatting = Formatting.Indented;
xml.Save(writer);
writer.Close();
fs.Close();
但是现在在创建文件 1 次和另外两次写入后的结果,文件看起来像这样:
<?xml version="1.0" encoding="utf-16"?>
<anndata>
<ann name="test1">
<weights>
<weight node1="7" node2="8" weight="-0.5699342" />
<weight node1="3" node2="8" weight="-0.2840658" />
<weight node1="0" node2="10" weight="-0.03812337" />
<weight node1="7" node2="10" weight="0.2714444" />
<weight node1="3" node2="10" weight="-0.2163633" />
<weight node1="0" node2="2" weight="0.8593098" />
<weight node1="7" node2="2" weight="-0.5274166" />
<weight node1="3" node2="2" weight="-0.1043958" />
<weight node1="8" node2="1" weight="0.5244942" />
<weight node1="10" node2="1" weight="0.7568867" />
<weight node1="2" node2="1" weight="0.7543423" />
<weight node1="8" node2="5" weight="-0.1524385" />
<weight node1="10" node2="5" weight="-0.09445882" />
<weight node1="2" node2="5" weight="-0.2441895" />
<weight node1="8" node2="11" weight="0.5473043" />
<weight node1="10" node2="11" weight="-0.1439976" />
<weight node1="2" node2="11" weight="0.1768849" />
<weight node1="0" node2="1" weight="-0.4702233" />
</weights>
</ann>
<ann name="test1"><weights><weight node1="7" node2="8" weight="-0.5699342" /><weight node1="3" node2="8" weight="-0.2840658" /><weight nod.... //no new lines here.
编辑2:
如果删除“fs.SetLength(0);” 它工作得更好,但现在<anndata>
根元素在我第二次写入它时被复制,并且 XmlDocument 在我第三次加载它以进行第三次写入时引发异常。