C# 创建、读取XML文件
前言:对于xml文件的创建,主要包括以下几个步骤:
1、新建Xml文档(XmlDocument),利用Xml文档的AppendChild属性为文档中添加节点
2、为xml文档添加Xml属性(XmlDeclaration)
3、为xml文档创建一个要素作为整个文档的根节点(CreateElement)
4、获取第3步创建的要素作为根节点(XmlNode;SelectSingleNode)
5、重复创建要素,并利用要素的AppendChild再添加子节点
6、将第5步创建的要素添加到XmlNode
7、将XmlNode添加到XmlDocument;
生成如下xml文件的示例代码如下:
/// <summary>
/// 创建xml工程文件
/// </summary>
/// <param name="xmlPath"></param>
/// <param name="projectStruct"></param>
public static void createProjectXML(string xmlPath)
{
try
{
XmlDocument pXmlDocument = new XmlDocument();
XmlDeclaration pXmlDeclaration = pXmlDocument.CreateXmlDeclaration("1.0", "gb2312", null);
pXmlDocument.AppendChild(pXmlDeclaration);
//加入一个根元素
XmlElement pElement = pXmlDocument.CreateElement("", "FieldAssistantProject", "");
pXmlDocument.AppendChild(pElement);
XmlNode pXmlRootNode = pXmlDocument.SelectSingleNode("FieldAssistantProject");//拿到根元素
//添加要素
XmlElement pXmlRootElement = pXmlDocument.CreateElement("baseMapData");
XmlElement pXmlElement = pXmlDocument.CreateElement("dataName");
pXmlElement.InnerText = "img";
pXmlRootElement.AppendChild(pXmlElement);
pXmlRootNode.AppendChild(pXmlRootElement);
pXmlDocument.Save(xmlPath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示");
}
}