protected string strXmlFile;
protected XmlDocument objXmlDoc = new XmlDocument();
public XmlControl(string XmlFile)
{
try
{
objXmlDoc.Load(XmlFile);
}
catch (System.Exception ex)
{
throw ex;
}
strXmlFile = XmlFile;
}
#region 增加一个节点
/// <summary>
/// 增加一个节点
/// </summary>
/// <param name="mainNode"></param>
/// <param name="nodeName"></param>
/// <param name="values"></param>
/// <returns></returns>
public bool AddNode(string mainNode,string nodeName,string values)
{
//如果主节点不存在的话,将会扔出一个错误
if(!this.IsExist(mainNode))
{
throw new Exception("生成XML时,发生错误,请确保模版XML文件一定正确");
}
//如果节点存在的情况下
XmlNode node = this.objXmlDoc.SelectSingleNode(mainNode);
XmlElement objElement = objXmlDoc.CreateElement(nodeName);
objElement.InnerText = values;
node.AppendChild(objElement);
return true;
}
#endregion
#region 修改一个节点的值,成功的话,返回True
/// <summary>
/// 修改一个节点的值,成功的话,返回True
/// </summary>
/// <param name="XmlPathNode"></param>
/// <param name="Content"></param>
public bool Replace(string node,string values)
{
if(this.IsExist(node))
{
objXmlDoc.SelectSingleNode(node).InnerText = values;
return true;
}
else
{
return false;
}
}
#endregion
#region 返回一个节点的值
/// <summary>
/// 返回一个节点的值
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public string GetNodeValue(string node)
{
if(this.IsExist(node))
{
return objXmlDoc.SelectSingleNode(node).InnerText;
}
else
{
return "";
}
}
#endregion
#region 判断一个节点是否存在
/// <summary>
/// 判断一个节点是否存在
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public bool IsExist(string node)
{
string[] nodes = node.Split('/');
XmlNodeList list = this.objXmlDoc.ChildNodes;
for(int i=0; i< nodes.Length;i++)
{
bool isFind = false;
for(int j = 0; j < list.Count; j++)
{
if(list[j].Name == nodes[i])
{
list = list[j].ChildNodes;
isFind = true;
break;
}
}
if(isFind == false)
{
return false;
}
}
return true;
}
#endregion