详细了解网址:
1.代码
using System;
using System.IO;
using System.Xml;
// 使用示例
class Program
{
static void Main()
{
XMLHelper xMLHelper = new XMLHelper();
}
}
public class XMLHelper
{
public XMLHelper()
{
ReadXml();
WriteXml();
}
private string mStrXml = "testBird.XML";
private void WriteXml()
{
XmlDocument doc = new XmlDocument();
// 创建XML声明
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8","yes");
doc.AppendChild(xmlDeclaration);
// 创建根元素
XmlElement root = doc.CreateElement("site");
doc.AppendChild(root);
// 创建子元素
XmlElement page = doc.CreateElement("page");
root.AppendChild(page);
//test
string str1 = "Birdxuan";
string str2 = "https://www.csdn.com";
string str3 = "XXXX";
string str4 = "testXml";
// 创建并添加子元素
AddElement(doc, page, "name", str1);
AddElement(doc, page, "url", str2);
AddElement(doc, page, "logo", str3);
AddElement(doc, page, "desc", str4);
// 保存XML文件
doc.Save(mStrXml);
}
private void ReadXml()
{
if (File.Exists(mStrXml))
{
XmlDocument doc = new XmlDocument();
doc.Load(mStrXml);
XmlNode netConfigNode = doc.SelectSingleNode("/site/page");
if (netConfigNode != null)
{
Console.WriteLine(GetNodeValue(netConfigNode, "name"));
Console.WriteLine(GetNodeValue(netConfigNode, "url"));
Console.WriteLine(GetNodeValue(netConfigNode, "logo"));
Console.WriteLine(GetNodeValue(netConfigNode, "desc"));
}
}
}
private string GetNodeValue(XmlNode parentNode, string nodeName)
{
XmlNode node = parentNode.SelectSingleNode(nodeName);
return node != null ? node.InnerText : "未找到";
}
private void AddElement(XmlDocument doc, XmlElement parent, string name, string value)
{
XmlElement element = doc.CreateElement(name);
element.InnerText = value;
parent.AppendChild(element);
if (name == "name")
{
XmlComment comment = doc.CreateComment("描述信息1");
parent.InsertBefore(comment, element);
}
else if (name == "url")
{
XmlComment comment = doc.CreateComment("描述信息2");
parent.InsertBefore(comment, element);
}
else if (name == "logo")
{
XmlComment comment = doc.CreateComment("描述信息3");
parent.InsertBefore(comment, element);
}
else if (name == "desc")
{
XmlComment comment = doc.CreateComment("描述信息4");
parent.InsertBefore(comment, element);
}
}
}
2.结果