您的位置:首页 > 产品设计 > UI/UE

Building XML File in C#

2020-02-17 05:14 302 查看
Why?
Though I found a lot of information on how to read a XML file, I wasn't able to find a complete solution for building XML structure and writing it to file system for my project. I hope this tutorial (or code sample) is helpful to some people.

For Whom?
This tutorial is designed for people with basic XML knowledge, to serve as a reference when building a XML file, the idea is very simple. Finding all the classes, methods needed is actually what takes time, thus the tutorial concentrates on C# language.

Different from writing a regular file.
When we open a file to write, there are many options available: override if already exists, append, etc. It surprises me that there is no single class in C# that does the following: "Read following XML file, if the XML file doesn't exist, create new XML file (Correct me if I am wrong)." Either XmlTextWriter or XmlDocument satisfy the requirement, the combination of the two works well.

Code Sample


Sample Output



using System.Xml;

void WriteXML()
{
try
{
//pick whatever filename with .xml extension
string filename = "XML"+DateTime.Now.Day + ".xml";

XmlDocument xmlDoc = new XmlDocument();

try
{
xmlDoc.Load(filename);
}
catch(System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("Root");
//If WriteProcessingInstruction is used as above,
//Do not use WriteEndElement() here
//xmlWriter.WriteEndElement();
//it will cause the <Root></Root> to be <Root />
xmlWriter.Close();
xmlDoc.Load(filename);
}
XmlNode root = xmlDoc.DocumentElement;
XmlElement childNode = xmlDoc.CreateElement("childNode");
XmlElement childNode2 = xmlDoc.CreateElement("SecondChildNode");
XmlText textNode = xmlDoc.CreateTextNode("hello");
textNode.Value = "hello, world";

root.AppendChild(childNode);
childNode.AppendChild(childNode2);
childNode2.SetAttribute("Name", "Value");
childNode2.AppendChild(textNode);

textNode.Value = "replacing hello world";
xmlDoc.Save(filename);
}
catch(Exception ex)
{
WriteError(ex.ToString());
}
}

void WriteError(string str)
{
outputBox.Text = str;
}

转载于:https://www.cnblogs.com/xinbin/archive/2006/08/18/480821.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
diaotuo1943 发布了0 篇原创文章 · 获赞 0 · 访问量 184 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: