我知道这个主题以前已经出过,但我似乎无法弄清楚如何做到这一点,即使有关于它的所有上一篇文章。
所以在我的代码中,我正在使用一些东西创建和填充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();
但现在是在创建文件和另外两篇文章之后的结果,该文件看起来像这样:
<?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.
EDIT2:
如果删除“fs.SetLength(0);”它工作得更好,但是现在<anndata>
根元素在我第二次写入时被复制了,而XmlDocument在第三次加载第三次写入时会产生异常。
答案 0 :(得分:0)
使用xml文档尝试这样做的方式看起来很好。尝试从您的文件中读取文档(并关闭文件),然后将文档作为单独的步骤保存回文件(而不是使用读/写文件并尝试在加载和保存步骤之间截断它)
除此之外,在您要求保存之前,只需检查您是否在文档中设置了正确的格式设置属性。