C# 本地xml文件进行增删改查
项目添加xml文件:facexml.xml,并复制到输出目录
facexml.xml
<?xml version="1.0" encoding="utf-8"?>
<faces>
<face>
<faceid></faceid>
<facebyte>/facebyte>
</face>
</faces>
项目添加xmlhelper帮助类
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.xml;
using system.xml.linq;
namespace avoidmisplace
{
public class xmlhelper
{
//项目输出目录的facexml.xl文件位置
public static string facepath = appdomain.currentdomain.basedirectory + "facexml.xml";
//查询是否存在faceid值为num的节点
public static bool queryfacexml(string num)
{
try
{
xdocument xml = xdocument.load(facepath);
xelement face = (from item in xml.element("faces").elements()
where item.element("faceid").value == num
select item).singleordefault();
if (face != null)
{
return true;
}
else
{
return false;
}
}
catch (exception ex)
{
return false;
}
}
//获取所有faces节点下facebyte值
public static list<string> getfacexml()
{
try
{
xdocument xml = xdocument.load(facepath);
var query = (from item in xml.element("faces").elements()
select item.element("faceid").value).tolist();
return query;
}
catch (exception)
{
return null;
}
}
//查询faceid值为num的节点对应facebyte值,
public static byte[] readfacexml(string num)
{
try
{
xdocument xml = xdocument.load(facepath);
var query = (from item in xml.element("faces").elements()
where item.element("faceid").value == num
select item).singleordefault();
return query.element("facebyte").value;
}
catch (exception ex)
{
return null;
}
}
//新增一个face节点写入键值对
public static bool writefacexml(string num, byte[] array)
{
try
{
xdocument xml = xdocument.load(facepath);
xelement face = new xelement("face", new xelement("faceid", num), new xelement("facebyte", array));
xml.element("faces").add(face);
xml.save(facepath);
//loghelper.debug("xml添加:" + num + ",成功");
return true;
}
catch (exception ex)
{
//loghelper.error("xml添加:" + num + "," + ex.message);
return false;
}
}
//删除faceid值为num的节点
public static bool delfacexml(string num)
{
try
{
xdocument xml = xdocument.load(facepath);
xelement face = (from item in xml.element("faces").elements()
where item.element("faceid").value == num
select item).singleordefault();
if (face != null)
{
face.remove();
xml.save(facepath);
//loghelper.debug("xml删除:" + num + ",成功");
return true;
}
else
{
//loghelper.debug("xml无:" + num);
return false;
}
}
catch (exception ex)
{
//loghelper.error("xml删除:" + num + "," + ex.message);
return false;
}
}
}
}