最近学习了C# XML的读写,现在记录下来。代码中有详细注释,看注释应该就清楚了。
先上写XML的代码:
public static void XmlWrite()
{
String path = GetPath();
XmlDocument xmlDoc = new XmlDocument();
//创建类型声明节点
XmlNode node=xmlDoc.CreateXmlDeclaration("1.0","utf-8","");
xmlDoc.AppendChild(node);
//创建根节点
XmlNode root = xmlDoc.CreateElement("Setting");
xmlDoc.AppendChild(root);
//创建节点node1,名为writer1
XmlNode node1 = xmlDoc.CreateNode(XmlNodeType.Element, "writer1", null);
//创建属性attr01,名为name
XmlNode attr01 = xmlDoc.CreateNode(XmlNodeType.Attribute, "name", null);
attr01.Value = "amber";//设置属性attr01的值
node1.Attributes.SetNamedItem(attr01);//把属性attr01添加到节点node1
//创建属性attr02,名为age
XmlNode attr02 = xmlDoc.CreateNode(XmlNodeType.Attribute, "age", null);
attr02.Value = "28";
node1.Attributes.SetNamedItem(attr02);
//创建节点node1的子节点
CreateNode(xmlDoc, node1, "Book1", "android");
CreateNode(xmlDoc, node1, "Book2", "ios");
CreateNode(xmlDoc, node1, "Book3", "winform");
root.AppendChild(node1);
//创建节点node2,名为writer2
XmlNode node2 = xmlDoc.CreateNode(XmlNodeType.Element, "writer2", null);
//创建属性attr1,名为name
XmlNode attr1 = xmlDoc.CreateNode(XmlNodeType.Attribute, "name", null);
attr1.Value = "amberoot";
node2.Attributes.SetNamedItem(attr1);
XmlNode attr2 = xmlDoc.CreateNode(XmlNodeType.Attribute, "age", null);
attr2.Value = "32";
node2.Attributes.SetNamedItem(attr2);
//创建节点node2的子节点
CreateNode(xmlDoc, node2, "Book1", "hi");
CreateNode(xmlDoc, node2, "Book2", "hello");
CreateNode(xmlDoc, node2, "Book3", "hey");
root.AppendChild(node2);
try
{
xmlDoc.Save(path);
}
catch (Exception e)
{
//显示错误信息
Console.WriteLine(e.Message);
}
//Console.ReadLine();
}
public static void CreateNode(XmlDocument xmlDoc,XmlNode parentNode,string name,string value)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value; //设置节点的值
parentNode.AppendChild(node);
}
结果:
public static void readXml()
{
String path = GetPath();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNode no = xmlDoc.SelectSingleNode("Setting");//获取根节点
XmlNodeList nodeList = no.ChildNodes;//获取根节点no的所有子节点
foreach (XmlNode nod0 in nodeList)
{
XmlElement element = (XmlElement)nod0;//获取节点
if (element.Name == "writer2")//element.Name获取节点element的节点名
{
XmlNodeList elementList = element.ChildNodes;//element.ChildNodes获取节点element中的所有子节点
foreach (XmlNode nod1 in elementList)
{
if (nod1.Name == "Book1")//nod1.Name获取节点nod1的节点名
{
String nod1_value = nod1.InnerText;//nod1.InnerText获取节点nod1的值
}
}
}
}
}