C# 中 XMLwriter 的缩进和换行命令
我正在将一些数据写入 XML 文件...但是当我打开它时,所有值都在一行中...如何以可读格式写入它?即每个节点都在新行和缩进中?
FileStream fs = new FileStream("myfile.xml", FileMode.Create);
XmlWriter w = XmlWriter.Create(fs);
w.WriteStartDocument();
w.WriteStartElement("myfile");
w.WriteElementString("id", id.Text);
w.WriteElementString("date", dateTimePicker1.Text);
w.WriteElementString("version", ver.Text);
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();
I am writing some data to XML file...but when I open it all the values are in a single line...how can write it in readable format?ie each node in new line and indentation?
FileStream fs = new FileStream("myfile.xml", FileMode.Create);
XmlWriter w = XmlWriter.Create(fs);
w.WriteStartDocument();
w.WriteStartElement("myfile");
w.WriteElementString("id", id.Text);
w.WriteElementString("date", dateTimePicker1.Text);
w.WriteElementString("version", ver.Text);
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用
XmlTextWriter
而不是XmlWriter
,然后设置Indentation
属性。示例
在 @jumbo 注释之后,这也可以像在 .NET 2 中一样实现。
Use a
XmlTextWriter
instead ofXmlWriter
and then set theIndentation
properties.Example
Following @jumbo comment, this could also be implemented like in .NET 2.
您需要首先创建一个指定缩进的 XmlWriterSettings 对象,然后在创建 XmlWriter 时,在路径后面传入 XmlWriterSettings。
此外,我使用
using
块让 C# 处理资源的处置,这样我就不必担心在异常时丢失任何资源。You need to first create an XmlWriterSettings object that specifies your indentation, then when creating your XmlWriter, pass in the XmlWriterSettings after your path.
Additionally, I use the
using
block to let C# handle the disposing of my resources so that I don't need to worry about losing any resources on an exception.检查设置属性:
编辑:您不能直接设置它:
Check the Settings property:
Edit: You can't set it directly:
设置 XmlTextWriter 的格式属性:
Set the Formatting Property of the XmlTextWriter:
使用设置如下:
这将让您到达您想要的位置,但是,您不必使用MemoryStream,重要的部分是设置。
Use Settings As follow:
This will get you where you want, though, you don't have to use MemoryStream, the importent part is the settings.
使用 XmlWriter 和 XmlWriterSettings 直接写入文件的小型 VB.NET 版本:
检查 doco 中的其他设置和文件覆盖选项,但这很干净,并且在很多情况下都可以按预期工作。
A little VB.NET version using XmlWriter plus XmlWriterSettings direct to file:
Check the doco for other settings and file overwrite options but this is clean and works as expected in lots of situations.