xml 操作

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Configuration;
namespace JjbPublic
{
    
class XmlOperations
    {
        XmlDocument XmlDoc 
= null;
        
string CurFilePath = null;
        
public XmlOperations(string XmlFilePath)
        {
            XmlDoc 
= OpenXmlFile(XmlFilePath);
            CurFilePath 
= XmlFilePath;
        }
        
public XmlOperations(XmlDocument XmlDocObj)
        {
            XmlDoc 
= XmlDocObj;
        }
        
/// <summary>
        
/// 返回正在处理的XmlDocument对象
        
/// </summary>
        public XmlDocument ProcessingXmlDocument
        {
            
get
            {
                
return XmlDoc;
            }
        }
        
public static XmlDocument OpenXmlFile(string FilePath)
        {
            XmlDocument RetXmlDoc 
= new XmlDocument();
            RetXmlDoc.Load(FilePath);
            
return RetXmlDoc;
        }
        
/// <summary>
        
/// 
        
/// </summary>
        
/// <param name="filePath"></param>
        
/// <param name="rootElementName">根接点名称</param>
        
/// <returns>NULL or error message.</returns>
        public static string CreateXmlFile(string FilePath, string RootElementName)
        {
            
string RetInfo = null;
            XmlDocument SaveXmlDoc 
= new XmlDocument();
            
try
            {
                SaveXmlDoc.InsertBefore(SaveXmlDoc.CreateNode(XmlNodeType.Element, RootElementName, 
null), SaveXmlDoc.DocumentElement);
                SaveXmlDoc.InsertBefore(SaveXmlDoc.CreateXmlDeclaration(
"1.0""utf-8"null), SaveXmlDoc.DocumentElement);
                SaveXmlDoc.InsertBefore(SaveXmlDoc.CreateComment(ConfigurationManager.AppSettings[
"copyrightInfo"].Replace("[br]"" ")), SaveXmlDoc.DocumentElement);
                SaveXmlDoc.Save(FilePath);
            }
            
catch (Exception err)
            {
                RetInfo 
= err.Message;
            }
            
return RetInfo;
        }
        
public static XmlDocument CreateXmlFile(string RootElementName)
        {
            XmlDocument CreaXmlDoc 
= new XmlDocument();
            CreaXmlDoc.InsertBefore(CreaXmlDoc.CreateNode(XmlNodeType.Element, RootElementName, 
null), CreaXmlDoc.DocumentElement);
            CreaXmlDoc.InsertBefore(CreaXmlDoc.CreateXmlDeclaration(
"1.0""utf-8"null), CreaXmlDoc.DocumentElement);
            CreaXmlDoc.InsertBefore(CreaXmlDoc.CreateComment(ConfigurationManager.AppSettings[
"copyrightInfo"].Replace("[br]"" ")), CreaXmlDoc.DocumentElement);
            
return CreaXmlDoc;
        }
        
/// <summary>
        
/// 
        
/// </summary>
        
/// <param name="parentNodeXPathExp">将要插入接点的父接点的XPath表达式</param>
        
/// <param name="nodeName"></param>
        
/// <param name="propertyName"></param>
        
/// <param name="propertyValue"></param>
        
/// <param name="nodeInnerText"></param>
        
/// <returns>NULL or error message.</returns>
        public string InsertNode(string ParentNodeXPathExp, string NodeName, string[] PropertyName, string[] PropertyValue, string NodeInnerText)
        {
            
string RetInfo = null;
            XmlNode xn 
= XmlDoc.SelectSingleNode(ParentNodeXPathExp);
            
if (xn != null)
            {
                
try
                {
                    xn.AppendChild(CreateNode(NodeName, PropertyName, PropertyValue, NodeInnerText));
                    RetInfo 
= SaveXmlDoc();
                }
                
catch (Exception err)
                {
                    RetInfo 
= err.Message;
                }
            }
            
else
            {
                RetInfo 
= "未找到指定的父接点。XPath语句:" + ParentNodeXPathExp;
            }
            
return RetInfo;
        }
        XmlNode CreateNode(
string NodeName, string[] PropertyName, string[] PropertyValue, string NodeInnerText)
        {
            XmlNode Xn 
= XmlDoc.CreateNode(XmlNodeType.Element, NodeName, null);
            
if (PropertyName != null)
            {
                XmlAttributeCollection xac 
= XmlDoc.DocumentElement.Attributes;
                XmlAttribute xa 
= null;
                
for (int i = 0; i < PropertyName.Length; i++)
                {
                    xa 
= XmlDoc.CreateAttribute(PropertyName[i]);
                    xa.Value 
= PropertyValue[i];
                    Xn.Attributes.Append(xa);
                }
            }
            Xn.InnerText 
= NodeInnerText;
            
return Xn;
        }
        
string SaveXmlDoc()
        {
            
if (CurFilePath != null)
            {
                
try
                {
                    XmlDoc.Save(CurFilePath);
                    
return "";
                }
                
catch (Exception err)
                {
                    
return err.Message;
                }
            }
            
return null;
        }
        
/// <summary>
        
/// 
        
/// </summary>
        
/// <param name="nodeXPathExp"></param>
        
/// <returns>NULL or error message.</returns>
        public string DeleteNode(string NodeXPathExp)
        {
            
string RetInfo = null;
            XmlNode Xn 
= XmlDoc.SelectSingleNode(NodeXPathExp);
            
if (Xn != null)
            {
                
if (Xn == XmlDoc.DocumentElement.FirstChild.ParentNode)
                {
                    RetInfo 
= "不能删除XML文档的根接点。";
                }
                
else
                {
                    
try
                    {
                        Xn.ParentNode.RemoveChild(Xn);
                        RetInfo 
= SaveXmlDoc();
                    }
                    
catch (Exception err)
                    {
                        RetInfo 
= err.Message;
                    }
                }
            }
            
else
            {
                RetInfo 
= "未找到指定的接点。XPath语句:" + NodeXPathExp;
            }
            
return RetInfo;
        }
        
/// <summary>
        
/// 
        
/// </summary>
        
/// <param name="xpathExp">XPath 表达式</param>
        
/// <returns></returns>
        public XmlNodeList SelectNodes(string XpathExp)
        {
            XmlNodeList xnl 
= XmlDoc.SelectNodes(XpathExp);
            
return xnl;
        }
        
#region 更新、删除和新增接点属性以及接点innerText
        
/// <summary>
        
/// 新增属性
        
/// 更新接点innerText
        
/// </summary>
        
/// <param name="xpathExp"></param>
        
/// <param name="addPropertyName"></param>
        
/// <param name="addPropertyValue"></param>
        
/// <param name="nodeInnerText"></param>
        
/// <returns></returns>
        public string AddNodesAttributes(string XpathExp, string[] AddPropertyName, string[] AddPropertyValue, string NodeInnerText)
        {
            
string oNodeInnerText = (NodeInnerText == null? "" : NodeInnerText;
            
return UpdateNodes(XpathExp, nullnullnull, AddPropertyName, AddPropertyValue, oNodeInnerText);
        }
        
/// <summary>
        
/// 新增属性
        
/// </summary>
        
/// <param name="xpathExp"></param>
        
/// <param name="addPropertyName"></param>
        
/// <param name="addPropertyValue"></param>
        
/// <returns></returns>
        public string AddNodesAttributes(string XpathExp, string[] AddPropertyName, string[] AddPropertyValue)
        {
            
return UpdateNodes(XpathExp, nullnullnull, AddPropertyName, AddPropertyValue, null);
        }
        
/// <summary>
        
/// 更新属性的名称和值
        
/// 更新接点的innerText
        
/// </summary>
        
/// <param name="xpathExp"></param>
        
/// <param name="oldPropertyName"></param>
        
/// <param name="newPropertyName"></param>
        
/// <param name="newPropertyValue"></param>
        
/// <param name="nodeInnerText"></param>
        
/// <returns></returns>
        public string UpdateNodesAttributes(string XpathExp, string[] OldPropertyName, string[] NewPropertyName, string[] NewPropertyValue, string NodeInnerText)
        {
            
string oNodeInnerText = (NodeInnerText == null? "" : NodeInnerText;
            
return UpdateNodes(XpathExp, OldPropertyName, NewPropertyName, NewPropertyValue, nullnull, oNodeInnerText);
        }
        
/// <summary>
        
/// 更新属性的名称和值
        
/// </summary>
        
/// <param name="xpathExp"></param>
        
/// <param name="oldPropertyName"></param>
        
/// <param name="newPropertyName"></param>
        
/// <param name="newPropertyValue"></param>
        
/// <returns></returns>
        public string UpdateNodesAttributes(string XpathExp, string[] OldPropertyName, string[] NewPropertyName, string[] NewPropertyValue)
        {
            
return UpdateNodes(XpathExp, OldPropertyName, NewPropertyName, NewPropertyValue, nullnullnull);
        }
        
/// <summary>
        
/// 更新属性的名称
        
/// </summary>
        
/// <param name="xpathExp"></param>
        
/// <param name="oldPropertyName"></param>
        
/// <param name="newPropertyName"></param>
        
/// <returns></returns>
        public string UpdateNodesAttributes(string XpathExp, string[] OldPropertyName, string[] NewPropertyName)
        {
            
return UpdateNodes(XpathExp, OldPropertyName, NewPropertyName, nullnullnullnull);
        }
        
/// <summary>
        
/// 删除属性
        
/// 更新接点innerText
        
/// </summary>
        
/// <param name="xpathExp"></param>
        
/// <param name="deletePropertyName"></param>
        
/// <param name="nodeInnerText"></param>
        
/// <returns></returns>
        public string DeleteNodesAttributes(string XpathExp, string[] DeletePropertyName, string NodeInnerText)
        {
            
string oNodeInnerText = (NodeInnerText == null? "" : NodeInnerText;
            
return UpdateNodes(XpathExp, DeletePropertyName, nullnullnullnull, oNodeInnerText);
        }
        
/// <summary>
        
/// 删除属性
        
/// </summary>
        
/// <param name="xpathExp"></param>
        
/// <param name="deletePropertyName"></param>
        
/// <returns></returns>
        public string DeleteNodesAttributes(string XpathExp, string[] DeletePropertyName)
        {
            
return UpdateNodes(XpathExp, DeletePropertyName, nullnullnullnullnull);
        }
        
/// <summary>
        
/// 更新接点innerText
        
/// </summary>
        
/// <param name="xpathExp"></param>
        
/// <param name="nodeInnerText"></param>
        
/// <returns></returns>
        public string UpdateNodesText(string XpathExp, string NodeInnerText)
        {
            
string oNodeInnerText = (NodeInnerText == null? "" : NodeInnerText;
            
return UpdateNodes(XpathExp, nullnullnullnullnull, oNodeInnerText);
        }
        
public string UpdateNodes(string XpathExp, string[] OldPropertyName, string[] NewPropertyName, string[] NewPropertyValue, string[] AddPropertyName, string[] AddPropertyValue, string NodeInnerText)
        {
            
string RetInfo = null;
            XmlNodeList xnl 
= XmlDoc.SelectNodes(XpathExp);
            XmlNode tXn 
= null;
            XmlAttribute xa 
= null;
            XmlAttribute xan 
= null;
            
string newPN = null;
            
int j = 0;
            
for (int i = 0; i < xnl.Count; i++)
            {
                
if (OldPropertyName != null)//删除和更新接点属性
                {
                    
for (j = 0; j < OldPropertyName.Length; j++)
                    {
                        xa 
= xnl[i].Attributes[OldPropertyName[j]];
                        
if (xa != null)
                        {
                            
if (NewPropertyName == null)
                            {
                                xnl[i].Attributes.Remove(xa);
                            }
                            
else
                            {
                                newPN 
= NewPropertyName[j];
                                
if (newPN == null || newPN == "")//remove attribute
                                {
                                    xnl[i].Attributes.Remove(xa);
                                }
                                
else//update attribute name and value
                                {
                                    xan 
= XmlDoc.CreateAttribute(newPN);
                                    xan.Value 
= NewPropertyValue[j];
                                        
//xa.Value;
                                    xnl[i].Attributes.SetNamedItem(xan);
                                    xnl[i].Attributes.Remove(xa);
                                }
                            }
                        }
                    }
                }
                
if (AddPropertyName != null)//新增接点属性
                {
                    
for (j = 0; j < AddPropertyName.Length; j++)
                    {
                        xa 
= XmlDoc.CreateAttribute(AddPropertyName[j]);
                        
if (AddPropertyValue != null)
                        {
                            xa.Value 
= AddPropertyValue[j];
                        }
                        xnl[i].Attributes.Append(xa);
                    }
                }
                
if (NodeInnerText != null)
                {
                    tXn 
= xnl[i];
                    SetXmlNodeText(
ref tXn, NodeInnerText);
                }
                
//xnl[i].FirstChild = nodeInnerText;//更新接点innerText
            }
            RetInfo 
= SaveXmlDoc();
            
return RetInfo;
        }
        
void SetXmlNodeText(ref XmlNode opXN, string NewInnerText)
        {
            XmlNodeList Xnl 
= opXN.ChildNodes;
            
for (int i = 0; i < Xnl.Count; i++)
            {
                
if (Xnl[i].NodeType == XmlNodeType.Text)
                {
                    opXN.RemoveChild(Xnl[i]);
                }
            }
            opXN.InsertBefore(XmlDoc.CreateTextNode(NewInnerText), opXN.FirstChild);
        }
        
#endregion
    }
}

 

利用该类进行操作:

如果存在则更新,不存在进行写入操作。

[WebMethod(EnableSession = true)]
    
public string GetRandomStr(string LoginID)
    {
        
string GuidValueStr = Guid.NewGuid().ToString();
        Session[LoginID] 
= GuidValueStr;
        
return GuidValueStr;
        
//try
        
//{
        
//    string FileStr = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Config/Web.config");
        
//    XmlOperations XmlDoc = new XmlOperations(FileStr);
        
//    string GuidValueStr = Guid.NewGuid().ToString();
        
//    System.Xml.XmlNodeList Xnl = XmlDoc.SelectNodes(string.Format("//add[@key='{0}']", LoginID));
        
//    if (Xnl != null && Xnl.Count > 0)
        
//    {
        
//        string[] OldPropertyName = new string[1] { "value" };
        
//        string[] NewPropertyName = new string[1] { "value" };
        
//        string[] NewPropertyValue = new string[1] { GuidValueStr };
        
//        string RetValue = XmlDoc.UpdateNodes(string.Format("//add[@key='{0}']", LoginID), OldPropertyName, NewPropertyName, NewPropertyValue, null, null, null);
        
//        if (RetValue == "")//返回""为执行成功 否则 null  或者错误消息执行失败
        
//        {
        
//            return GuidValueStr;
        
//        }
        
//    }
        
//    else
        
//    {
        
//        string[] NewPropertyName = new string[2] { "key", "value" };
        
//        string[] NewPropertyValue = new string[2] { LoginID, GuidValueStr };
        
//        string RetValue = XmlDoc.InsertNode("//appSettings", "add", NewPropertyName, NewPropertyValue, null);
        
//        if (RetValue == "")//返回""为执行成功 否则 null  或者错误消息执行失败
        
//        {
        
//            return GuidValueStr;
        
//        }
        
//    }
        
//}
        
//catch(Exception Ex)
        
//{
        
//    LogFactory.LogWriteText("生成随机串的时候出现错误:"+Ex.Message);
        
//}
        
//return "-1";
    }

 

进行交易操作:

 

[WebMethod]
    
public string GetTradeInfo(int GoldAmount,string RandomStr )
    {
        
//如果RandomStr是合法的那么进行转换操作
        
//返回 BeanCount,RandomStr,ErrString
        string RetStr = string.Format("ErrCode={0},RandomStr={1},ErrMsg={2}""-1", RandomStr, "用户信息异常.");
        
string FileStr = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Config/Web.config");
        XmlOperations XmlDoc 
= new XmlOperations(FileStr);
        System.Xml.XmlNodeList Xnl 
= XmlDoc.SelectNodes(string.Format("//add[@value='{0}']", RandomStr));
        
if (Xnl != null && Xnl.Count > 0)
        {
            
int LoginID = Utils.StrToIntDef(Xnl[0].Attributes["key"].Value, -1);
            
if (LoginID == -1)
            {
                RetStr 
= string.Format("{0},{1},{2}""-1", RandomStr, "用户信息异常.");
            }
            
else
            {
                
int BeanCount = SysClass.GetExchangedAmount(GoldAmount, 1);//兑换后的游戏豆的数量。
                if (BeanCount == -1)
                {
                    RetStr 
= string.Format("{0},{1},{2}""-1", RandomStr, "转帐过程出现异常.");
                }
                
else
                {
                    XmlDoc.DeleteNode(
string.Format("//add[@value='{0}']", RandomStr));
                    RetStr 
= string.Format("{0},{1},{2}", BeanCount.ToString(), RandomStr, "");
                }
            }
        }
        
else
        {
            RetStr 
= string.Format("{0},{1},{2}""-1", RandomStr, "用户信息异常.");
        }
        
return RetStr;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值