LINQ for XML简单示例
LINQ,语言集成查询(Language Integrated Query)是一组用于c#和Visual Basic语言的扩展。它允许开发人员以与查询数据库相同的方式操作内存数据。从技术角度而言,LINQ定义了大约40个查询操作符,如select、from、in、where以及order by(C#中)。使用这些操作符可以编写查询语句。不过,这些查询还可以基于很多类型的数据,每个数据类型都需要一个单独的LINQ类型。
本文简单介绍使用LINQ技术来实现XML的基本操作,该实例包含两个类:XmlElementInfor和XmlHelper,具体代码实现如下:
public class XmlHelper { private string _filePath; public XmlHelper(string filePath) { _filePath = filePath; } /// <summary> /// 创建XML文件 /// </summary> public void CreateDocument() { XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("Root")); xdoc.Save(_filePath); } /// <summary> /// 向XML跟节点中添加元素 /// </summary> /// <param name="nodeName">元素名称</param> /// <param name="xelements">元素属性及内容</param> public void AddXmlNodeToRoot(string nodeName, params object[] xelements) { XElement rootNode = XElement.Load(_filePath); XElement newNode = new XElement(nodeName, xelements); rootNode.Add(newNode); rootNode.Save(_filePath); } /// <summary> /// 从XML跟节点删除元素及其子元素 /// </summary> /// <param name="nodeName">元素名称</param> /// <param name="IdElement">元素筛选条件</param> public void DeleteNodeFromRoot(string nodeName, XmlElementInfor IdElement) { XElement rootNode = XElement.Load(_filePath); IEnumerable<XElement> targetNodes = from target in rootNode.Descendants(nodeName) where target.Element(IdElement.Name).Value.Equals(IdElement.Value) select target; targetNodes.Remove(); rootNode.Save(_filePath); } /// <summary> /// 更新元素 /// </summary> /// <param name="nodeName">元素名称</param> /// <param name="IdElement">元素筛选条件</param> /// <param name="updateValue">需更新内容</param> public void UpdateNodeFromRoot(string nodeName, XmlElementInfor IdElement, XmlElementInfor[] updateValue) { XElement rootNode = XElement.Load(_filePath); IEnumerable<XElement> targetNodes = from target in rootNode.Descendants(nodeName) where target.Element(IdElement.Name).Value.Equals(IdElement.Value) select target; foreach (XElement node in targetNodes) { foreach (var item in updateValue) { node.Element(item.Name).SetValue(item.Value); } } rootNode.Save(_filePath); } /// <summary> /// 从根节点查询元素 /// </summary> /// <param name="nodeName">元素名称</param> /// <param name="IdElement">元素筛选条件</param> /// <returns></returns> public IEnumerable<XElement> QueryNodeFromRoot(string nodeName, XmlElementInfor IdElement) { XElement rootNode = XElement.Load(_filePath); IEnumerable<XElement> targetNodes = from target in rootNode.Descendants(nodeName) where target.Element(IdElement.Name).Value.Equals(IdElement.Value) select target; return targetNodes; } }
public class XmlElementInfor { private string _name; private string _value; public XmlElementInfor(string elementName, string elementValue) { _name = elementName; _value = elementValue; } public string Name { get { return _name; } } public string Value { get { return _value; } } }