本文介绍了在C#缩进和新行命令的XmlWriter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些数据,以XML文件...但是当我打开它的所有值都在单行...如何在可读的格式写?即在新的生产线和缩进各节点?

 的FileStream FS =新的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(版本,ver.Text);
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();


解决方案

使用的XmlTextWriter 而不是的XmlWriter ,然后将缩进属性。



示例



 字符串文件名= 将myfile.xml; 

使用(XmlTextWriter的的XmlWriter =新的XmlTextWriter
使用(的FileStream FILESTREAM =新的FileStream(文件名,FileMode.Create))
使用(StreamWriter的SW =新的StreamWriter(FILESTREAM))( SW))
{
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 4;

// ...写的元素
}


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();
解决方案

Use a XmlTextWriter instead of XmlWriter and then set the Indentation properties.

Example

string filename = "MyFile.xml";

using (FileStream fileStream = new FileStream(filename, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fileStream))
using (XmlTextWriter xmlWriter = new XmlTextWriter(sw))
{
  xmlWriter.Formatting = Formatting.Indented;
  xmlWriter.Indentation = 4;

  // ... Write elements
}

这篇关于在C#缩进和新行命令的XmlWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:18