public int setMax(string VarName)
{
//先查找次变量,如果没有,就新增,并设置最大枝为1,如果有则替换
XmlDocument XmlDoc=new XmlDocument();
XmlTextReader XmlReader=new XmlTextReader("D:/Max.xml");
bool Found=false;
try
{
while(XmlReader.Read())
{
if(XmlReader.LocalName==VarName)
{
Found=true;
break;
}
}
if(Found)//找到此变量
{
return 2; }
else //没有找到
{
XmlElement VarElement=XmlDoc.CreateElement("var");
//VarElement.InnerXml="<varName>"+VarName+"</varName><MaxValue>1</MaxValue>";
XmlElement NameElement=XmlDoc.CreateElement("varName");
NameElement.InnerText=VarName;
VarElement.AppendChild(NameElement);
XmlElement MaxValueElement=XmlDoc.CreateElement("MaxValue");
MaxValueElement.InnerText="1";
VarElement.AppendChild(MaxValueElement);
return 1;
}
}
catch(Exception Ex)
{
throw new Exception("生成ID出错!"+Ex.Message);
}
finally
{
if(XmlReader!=null)
{
XmlReader.Close();
}
} }

解决方案 »

  1.   

    改成这样也不性:
    public int setMax(string VarName)
    {
    //先查找次变量,如果没有,就新增,并设置最大枝为1,如果有则替换
    XmlTextReader XmlReader=new XmlTextReader("D:/Max.xml");
    bool Found=false;
    try
    {
    while(XmlReader.Read())
    {
    if(XmlReader.LocalName==VarName)
    {
    Found=true;
    break;
    }
    }
    if(XmlReader!=null)
    {
    XmlReader.Close();
    }
    if(Found)//找到此变量
    {
    return 2; }
    else //没有找到
    {
    XmlDocument XmlDoc=new XmlDocument();
    XmlDoc.Load("D:/Max.xml");
    XmlElement VarElement=XmlDoc.CreateElement("var");
    //VarElement.InnerXml="<varName>"+VarName+"</varName><MaxValue>1</MaxValue>";
    XmlElement NameElement=XmlDoc.CreateElement("varName");
    NameElement.InnerText=VarName;
    VarElement.AppendChild(NameElement);
    XmlElement MaxValueElement=XmlDoc.CreateElement("MaxValue");
    MaxValueElement.InnerText="1";
    VarElement.AppendChild(MaxValueElement);
    XmlDoc.Save("D:/Max.xml");
    return 1;
    }
    }
    catch(Exception Ex)
    {
    throw new Exception("生成ID出错!"+Ex.Message);
    } }
      

  2.   

    很多错误:1、你的XmlDocument根本没有加载过XML文档,你怎么操作啊。2、你没有把新的节点VarElement  AppendChild到你的XmlDocument3、你的XmlDocument没有保存