Linq技术二:Linq to XML及xml增删改查的不同实现方式

前端之家收集整理的这篇文章主要介绍了Linq技术二:Linq to XML及xml增删改查的不同实现方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Linq to XML是Linq三种操作中的一种,有多种不同方法可实现Linq对xml文件的操作,比如:XmlDocument,DataSet,XDocument,XElement,XMLReader。

命名空间:

System.XML;

System.XML.Linq;


传统操作方式是:

1. XmlDocument:用xpath遍历xml树找到需要操作的节点,然后再进行相应的操作。

2. DataSet:将xml文件加载到一个dataset里面,然后再操作data table的方法进行相应操作。

传统方式的缺点是操作起来不够简便。


看一个例子:

<?xml version="1.0" encoding="utf-8"?>
<Permission>
<right name="Rb5" value="32" description="罚单管理" type="bs" />
<right name="Rb4" value="16" description="报表管理" type="bs" />
<right name="Rb0" value="1" description="车辆信息管理" type="bs" />
<right name="Rb1" value="2" description="车载终端管理" type="bs" />
<right name="Rb2" value="4" description="用户权限管理" type="bs" />
<right name="Rb3" value="8" description="角色管理" type="bs" />
<right name="Rc0" value="1" description="车辆信息管理" type="cs" />
<right name="Rc1" value="2" description="车载终端管理" type="cs" />
</Permission>


XmlDocument操作:

//首先加载xml文件,这个可以放到构造函数里面

XmlDocument document = new XmlDocument();
document.Load(XmlFilePath);


//增、删、改、查的操作

#region Add,Update and Delete Methods

/// <summary>
/// Add new permission description
/// </summary>
/// <param name="name">the permission's name</param>
/// <param name="description">the permission's description</param>
public void AddNewPermission(string name,string description,string value,string type)
{
XmlElement element = null;
XmlAttribute attrName = null;
XmlAttribute attrValue = null;
XmlAttribute attrDes = null;
XmlAttribute attrType = null;

try
{
XmlElement root = document.DocumentElement;

element = document.CreateElement("right");
attrName = document.CreateAttribute("name");
attrValue = document.CreateAttribute("value");
attrDes = document.CreateAttribute("description");
attrType = document.CreateAttribute("type");

attrName.Value = name;
attrValue.Value = value;
attrDes.Value = description;
attrType.Value = type;
//element.InnerText = description;
element.SetAttributeNode(attrName);
element.SetAttributeNode(attrValue);
element.SetAttributeNode(attrDes);
element.SetAttributeNode(attrType);

root.InsertAfter(element,root.NextSibling);

document.Save(XmlFilePath);
}
catch (Exception ex)
{
throw ex;
}
}

/// <summary>
/// Remove the given permission
/// </summary>
/// <param name="rightName">the given permission's name</param>
public void RemoveGivenPermission(string rightName)
{
XmlNode node = null;
string strXpath = string.Empty;

try
{
strXpath = string.Format("/Permission/right[@name='{0}']",rightName);
node = document.DocumentElement.SelectSingleNode(strXpath);

if (node != null)
{
document.DocumentElement.RemoveChild(node);
document.Save(XmlFilePath);
}
}
catch (Exception ex)
{
throw ex;
}
}

/// <summary>
/// Edit the given permission's description
/// </summary>
/// <param name="rightName">the permission's name which need to be edit</param>
/// <param name="newDescription">new description</param>
public void EditGivenPermission(string newName,string oldName,string newDescription,string value)
{
XmlNode node = null;
string strXpath = string.Empty;
XmlElement newNode = null;
XmlAttribute attrName = null;
XmlAttribute attrValue = null;
XmlAttribute attrDescription = null;
XmlAttribute attrType = null;

try
{
strXpath = string.Format("/Permission/right[@name='{0}']",oldName);
node = document.DocumentElement.SelectSingleNode(strXpath);

newNode = document.CreateElement("right");
attrName = document.CreateAttribute("name");
attrValue = document.CreateAttribute("value");
attrType = document.CreateAttribute("type");
attrDescription = document.CreateAttribute("description");

attrName.Value = newName;
attrValue.Value = value;
attrDescription.Value = newDescription;
attrType.Value = node.Attributes["type"].Value;

newNode.SetAttributeNode(attrName);
newNode.SetAttributeNode(attrValue);
newNode.SetAttributeNode(attrDescription);
newNode.SetAttributeNode(attrType);

document.DocumentElement.ReplaceChild(newNode,node);
document.Save(XmlFilePath);
}
catch (Exception ex)
{
throw ex;
}
}

#endregion


DataSet操作:

#region Transform the XML file format into table format

public DataTable GetTableFormat()
{
try
{
DataSet ds = new DataSet();
ds.ReadXml(XmlFilePath);

return ds.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}

public void AddItemToXML(string name,string right)
{
try
{
DataSet ds = new DataSet();
DataTable dt = GetTableFormat();
DataRow dr = dt.NewRow();
dr[0] = name;
dr[1] = right;
dt.Rows.Add(dr);
ds.Tables.Add(dt);
ds.WriteXml(XmlFilePath);
}
catch (Exception ex)
{
throw ex;
}
}

public void DeleteItemToXML(string name)
{
try
{
DataSet ds = new DataSet();
DataTable dt = GetTableFormat();
DataRow[] dr = dt.Select("name == '"+ name +"'");
dt.Rows.Remove(dr[0]);
ds.Tables.Add(dt);
ds.WriteXml(XmlFilePath);
}
catch (Exception ex)
{
throw ex;
}
}

#endregion


Linq to XML的方式:

Linq to XML的方式就需要用到XElement操作了,XElement的扩展属性包含了Linq所有的功能,所以基本上把xml文件当作database或IEnumerable Object一样的数据源就行了。

//加载xml文件

XElement xmlDoc = XElement.Load(Path);

//查询节点

IEnumerable<XElement> lt = from n in xmlDoc.Elements("right")
where (string)n.Attribute("name") == code
select n;

String strReturn = lt.First<XElement>().Attribute("description").ToString();

//新增及修改

xmlDoc.SetElementValue(nodename,value);

//xml内容和字符串间的相互转换

StringBuilder strXmlContent = new StringBuilder();

strXmlContent.Append(XElement.Load(Path).ToString()); //xml Element转换成string;

xmlDoc = XElement.Parse(strXmlContent.ToString()); //String转换成XElement;


如果需要对xml文件进行验证,那么需要用到XDocument:

XmlSchemaSet schema = new XmlSchemaSet();

schema.add("","xxxx.xsd");

XDocument xmlDoc = XDocument.Load("xxx.xml");

xmlDoc.Validate(schema,(o,e) => { //

//匿名委托,处理你的验证业务逻辑

});


Linq to xml操作的其它特性还有事件,也就是说对xml节点的操作可以触发事件,这是其它方式所没有的:

XElement xmlDoc = root.Element("name");

xmlDoc.Changed += (object sender,XObjectChangeEventArgs e) =>
{
//throw new NotImplementedException();
//业务逻辑
};

XMLReader的操作,xmlreader提供向前只读读取xml数据流,并且提供异步读取方法,更多异步读取方法参考: http://msdn.microsoft.com/zh-cn/library/system.xml.xmlreader.aspx


以上是三种不同的操作方法,Linq提供了更多功能,并能快速定位到任何节点,只需要了解Linq的语法就可以操作,不需要了解xpath等规则。



猜你在找的XML相关文章