在之前做Java项目时经常用到XML文件的读取写入操作,在学习C#的过程中偶然想起来xml,看了看和Java的基本一致。简单做个util类来进行测试验证。
使用的命名空间是System.Xml
class XMLUtils
{
/// <summary>
/// 生成XML文件
/// </summary>
/// <param name="xmlFilePath">XML文件地址</param>
/// <param name="parentEle">根节点名</param>
/// <param name="firstDic">第一层子节点名和属性的集合</param>
/// <param name="secondDic">第二层子节点的集合</param>
public static void GenerateXMLFile(string xmlFilePath, string parentEle, List<Dictionary<string, string>> firstDic, List<Dictionary<string, string>> secondDic)
{
try
{
//初始化一个xml实例
XmlDocument myXmlDoc = new XmlDocument();
//创建xml的根节点
XmlElement rootElement = myXmlDoc.CreateElement(parentEle);
//将根节点加入到xml文件中(AppendChild)
myXmlDoc.AppendChild(rootElement);
int i = 0;
foreach (Dictionary<string, string> fkeyValues in firstDic)
{
//初始化第一层的子节点
XmlElement firstLevelElement1 = myXmlDoc.CreateElement(fkeyValues["firstChildEle"]);
//填充第一层的子节点的属性值(SetAttribute)
foreach (KeyValuePair<string, string> keyValue in fkeyValues)
{
if (!keyValue.Key.Equals("firstChildEle"))
firstLevelElement1.SetAttribute(keyValue.Key, keyValue.Value);
}
rootElement.AppendChild(firstLevelElement1);
foreach (KeyValuePair<string, string> keyValue in secondDic[i])
{
//初始化第二层的子节点
XmlElement secondLevelElement11 = myXmlDoc.CreateElement(keyValue.Key);
//填充第二层的子节点的值(InnerText)
secondLevelElement11.InnerText = keyValue.Value;
firstLevelElement1.AppendChild(secondLevelElement11);
}
i++;
}
//将xml文件保存到指定的路径下
myXmlDoc.Save(xmlFilePath);
Console.WriteLine("创建"+xmlFilePath+"文件成功");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// 获取XML文件中的内容
/// </summary>
/// <param name="xmlFilePath">XML文件地址</param>
/// <param name="parentEle">根节点名</param>
public static void GetXMLInformation(string xmlFilePath, string parentEle)
{
try
{
//初始化一个xml实例
XmlDocument myXmlDoc = new XmlDocument();
//加载xml文件(参数为xml文件的路径)
myXmlDoc.Load(xmlFilePath);
//获得第一个姓名匹配的节点(SelectSingleNode):此xml文件的根节点
XmlNode rootNode = myXmlDoc.SelectSingleNode(parentEle);
//分别获得该节点的InnerXml和OuterXml信息
string innerXmlInfo = rootNode.InnerXml.ToString();
string outerXmlInfo = rootNode.OuterXml.ToString();
//获得该节点的子节点(即:该节点的第一层子节点)
XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
foreach (XmlNode node in firstLevelNodeList)
{
//获得该节点的属性集合
XmlAttributeCollection attributeCol = node.Attributes;
foreach (XmlAttribute attri in attributeCol)
{
//获取属性名称与属性值
string name = attri.Name;
string value = attri.Value;
Console.WriteLine("{0} = {1}", name, value);
}
//判断此节点是否还有子节点
if (node.HasChildNodes)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
//获取该节点的第二个子节点(用数组下标获取)
XmlNode secondLevelNode2 = node.ChildNodes[i];
string name = secondLevelNode2.Name;
string innerText = secondLevelNode2.InnerText;
Console.WriteLine("{0} = {1}", name, innerText);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// 为XML子节点添加新的节点信息,属性可为空
/// </summary>
/// <param name="xmlFilePath">XML文件地址</param>
/// <param name="elementKey">新增子节点名称</param>
/// <param name="elementValue">新增子节点值</param>
/// <param name="attributeKey">新增子节点属性名(可为null)</param>
/// <param name="attributeValue">新增子节点属性值(可为null)</param>
public static void AddXmlInformation(string xmlFilePath, string elementKey, string elementValue, string attributeKey, string attributeValue)
{
try
{
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.Load(xmlFilePath);
//添加一个带有属性的节点信息
foreach (XmlNode node in myXmlDoc.FirstChild.ChildNodes)
{
XmlElement newElement = myXmlDoc.CreateElement(elementKey);
newElement.InnerText = elementValue;
if (attributeKey != null && !"".Equals(attributeKey))
{
if (attributeValue != null && !"".Equals(attributeValue))
{
newElement.SetAttribute(attributeKey, attributeValue);
}
}
node.AppendChild(newElement);
}
//保存更改
myXmlDoc.Save(xmlFilePath);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// 修改子节点属性值
/// </summary>
/// <param name="xmlFilePath">XML文件地址</param>
/// <param name="attributeKey">属性名</param>
/// <param name="attributeValue">原属性值</param>
/// <param name="newValue">欲修改属性值</param>
public static void ModifyXmlAttributes(string xmlFilePath, string attributeKey, string attributeValue, string newValue)
{
try
{
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.Load(xmlFilePath);
XmlNode rootNode = myXmlDoc.FirstChild;
XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
foreach (XmlNode node in firstLevelNodeList)
{
//修改此节点的属性值
if (node.Attributes[attributeKey].Value.Equals(attributeValue))
{
node.Attributes[attributeKey].Value = newValue;
}
}
//要想使对xml文件所做的修改生效,必须执行以下Save方法
myXmlDoc.Save(xmlFilePath);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// 修改XML子节点下的子节点信息
/// </summary>
/// <param name="xmlFilePath">XML文件地址</param>
/// <param name="elementKey">子节点名</param>
/// <param name="elementValue">子节点值</param>
/// <param name="newValue">欲修改的值</param>
public static void ModifyXmlElement(string xmlFilePath, string elementKey, string elementValue, string newValue)
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);
//获取根节点的所有子节点
XmlNodeList nodeList = xmlDoc.FirstChild.ChildNodes;
foreach (XmlNode xn in nodeList)//遍历所有子节点
{
//将子节点类型转换为XmlElement类型
XmlElement xe = (XmlElement)xn;
XmlNodeList nls = xe.ChildNodes;
//继续遍历获取xe子节点的所有子节点
foreach (XmlNode xn1 in nls)
{
XmlElement xe2 = (XmlElement)xn1;
if (xe2.Name == elementKey && xe2.InnerText == elementValue)
{
xe2.InnerText = newValue;
//break;
}
}
}
xmlDoc.Save(xmlFilePath);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// 删除对应属性和属性值的子节点
/// </summary>
/// <param name="xmlFilePath">XML文件地址</param>
/// <param name="attributeKey">子节点的属性名</param>
/// <param name="attributeValue">子节点的属性值</param>
public static void DeleteXmlNode(string xmlFilePath, string attributeKey, string attributeValue)
{
try
{
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.Load(xmlFilePath);
foreach (XmlNode node in myXmlDoc.FirstChild.ChildNodes)
{
if (node.Attributes[attributeKey].Value.Equals(attributeValue))
{
//删除子节点下的所有子节点
node.RemoveAll();
//删除子节点
node.ParentNode.RemoveChild(node);
}
}
//保存对xml文件所做的修改
myXmlDoc.Save(xmlFilePath);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
测试
class Program
{
static void Main(string[] args)
{
//创建XML文件
createXML();
//获取XML文件的节点内容
getXMLNode();
//新增子节点信息
addXMLElement();
getXMLNode();
//修改子节点信息
modifyXMLElement();
getXMLNode();
//根据属性删除子节点
deleteXMLNode();
getXMLNode();
Console.ReadLine();
}
static void createXML()
{
Dictionary<string, string> firstDic1 = new Dictionary<string, string>();
Dictionary<string, string> firstDic2 = new Dictionary<string, string>();
Dictionary<string, string> secondDic1 = new Dictionary<string, string>();
Dictionary<string, string> secondDic2 = new Dictionary<string, string>();
firstDic1.Add("firstChildEle", "computer");
firstDic1.Add("ID", "11111111");
firstDic1.Add("Description", "Made in China");
firstDic2.Add("firstChildEle", "computer");
firstDic2.Add("ID", "22222222");
firstDic2.Add("Description", "Made in Japan");
secondDic1.Add("name", "Lenovo");
secondDic1.Add("price", "5500");
secondDic2.Add("name", "Dell");
secondDic2.Add("price", "10000");
List<Dictionary<string, string>> firstDicList = new List<Dictionary<string, string>>();
List<Dictionary<string, string>> secondDicList = new List<Dictionary<string, string>>();
firstDicList.Add(firstDic1);
firstDicList.Add(firstDic2);
secondDicList.Add(secondDic1);
secondDicList.Add(secondDic2);
string path = System.IO.Directory.GetCurrentDirectory();
path = path.Substring(0, path.Length - 10);
string filePath = path + "/XMLFile/computerXML.xml";
if (!File.Exists(filePath))
{
FileStream fileStream = File.Create(filePath);
fileStream.Close();
}
XMLUtils.GenerateXMLFile(filePath, "computers", firstDicList, secondDicList);
}
static void getXMLNode()
{
string path = System.IO.Directory.GetCurrentDirectory();
path = path.Substring(0, path.Length - 10);
string filePath = path + "/XMLFile/computerXML.xml";
if (File.Exists(filePath))
{
XMLUtils.GetXMLInformation(filePath, "computers");
}
}
static void addXMLElement()
{
string path = System.IO.Directory.GetCurrentDirectory();
path = path.Substring(0, path.Length - 10);
string filePath = path + "/XMLFile/computerXML.xml";
if (File.Exists(filePath))
{
XMLUtils.AddXmlInformation(filePath, "color", "black", "", "");
}
}
static void modifyXMLElement()
{
string path = System.IO.Directory.GetCurrentDirectory();
path = path.Substring(0, path.Length - 10);
string filePath = path + "/XMLFile/computerXML.xml";
if (File.Exists(filePath))
{
XMLUtils.ModifyXmlElement(filePath, "color", "black", "white");
}
}
static void deleteXMLNode()
{
string path = System.IO.Directory.GetCurrentDirectory();
path = path.Substring(0, path.Length - 10);
string filePath = path + "/XMLFile/computerXML.xml";
if (File.Exists(filePath))
{
XMLUtils.DeleteXmlNode(filePath, "ID", "11111111");
}
}
}
结果:可以正常使用。