XML操作方法

来源:互联网 发布:点击淘宝旺旺没反应 编辑:程序博客网 时间:2024/05/09 18:33
///方法名:XPathQueryFromXml
  
  ///输入参数:
  /// pFileName:文件名
  /// pRoot:元素的根
  /// pAttribute:属性名
  /// pAttributeValue:属性值
  ///返回值:该元素的值,string类型
  
  public XmlNode LoadValue(string xpath,int index)
  {
   XmlNodeList nl=xml.SelectNodes(xpath);
   return nl.Item(index);
  }
  public  string XPathFromXml(string pRoot,string pAttribute,string pAttributeValue)
  {
   string sValue="Error.";
   string sXPath="//"+pRoot+"/*[@"+pAttribute+"='"+pAttributeValue+"']";
   try
   {
    XmlNode nd=xml.SelectSingleNode(sXPath);
    sValue=nd.InnerText.ToString();
   }
   catch(Exception E)
   {
    ApplicationLog.WriteLog(E.ToString());
   }
   return sValue;
  }
  
  ///方法名:AddValueToXml      
  ///功能:将指定的xmlnode加入指定文件的指定位置
  ///输入参数:
  /// pFileName:文件名
  /// pElementName:元素名
  /// pValue:元素的值
  /// pAttribute:属性名
  /// pAttributeValue:属性值
  /// pRoot:元素的根
  ///返回值:无
  public  void AddValueToXML(string pRoot,string pElementName,string pAttribute,string pAttributeValue,string pValue)
  {
   
   try
   {
    XmlElement root=xml.DocumentElement;
    XmlNode nd=root[pRoot];
    XmlElement nEl=xml.CreateElement(pElementName);
    nEl.SetAttribute(pAttribute,pAttributeValue);
    nEl.InnerText=pValue;
    nd.AppendChild(nEl); 
    xml.Save(m_ConfigFileName);
   }
   catch(Exception E)
   {
    ApplicationLog.WriteLog(E.ToString());
   }
  }
  ///方法名:UpdateValueToXml       by jsz at 2003.1.23
  ///功能:修改指定文件的指定位置,根据元素名+属性值匹配
  ///输入参数:
  /// pFileName:文件名
  /// pRoot:元素的根
  /// pElementName:元素名
  /// pAttribute:属性名
  /// pAttributeValue:属性值
  /// pValue:要更换的元素值
  ///返回值:bool类型,标识成功与否
  public  bool UpdateValueToXML(string pRoot,string pElementName,string pAttribute,string pAttributeValue,string pValue)
  {
   
   bool sValue=false;
   string sXPath="//"+pRoot+"/"+pElementName+"[@"+pAttribute+"='"+pAttributeValue+"']";
   try
   {
    XmlNode nd=xml.SelectSingleNode(sXPath);
    nd.InnerText =pValue; 
    xml.Save(m_ConfigFileName);
    sValue=true;
   }
   catch(Exception E)
   {
    ApplicationLog.WriteLog(E.ToString());
   }
   return sValue;
  }
  ///方法名:DeleteFromXml       by jsz at 2003.1.23
  ///功能:从指定文件的指定位置删除节点,根据元素名+属性值匹配
  ///输入参数:
  /// pFileName:文件名
  /// pRoot:元素的根
  /// pElementName:元素名
  /// pAttribute:属性名
  /// pAttributeValue:属性值
  ///返回值:bool类型,标识成功与否
  public  bool DeleteFromXML(string pRoot,string pElementName,string pAttribute,string pAttributeValue)
  {
   
   bool sValue=false;
   string sXPath="//"+pRoot+"/"+pElementName+"[@"+pAttribute+"='"+pAttributeValue+"']";
   string sXPathRoot="//"+pRoot;
   try
   {
    XmlNode nd=xml.SelectSingleNode(sXPath);
    XmlNode root=xml.SelectSingleNode(sXPathRoot);
    nd.RemoveChild(nd); 
    xml.Save(m_ConfigFileName);
    sValue=true;
   }
   catch(Exception E)
   {
    ApplicationLog.WriteLog(E.ToString());
   }
   return sValue;
  }