項目添加XML文件:FaceXml.xml,並複製到輸出目錄 FaceXml.xml <?xml version="1.0" encoding="utf-8"?> <faces> <face> <faceid></faceid> <facebyte>/facebyte> </face></faces ...
項目添加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;
}
}
}
}