LinqToXML添加 XML元素 及修改属性值

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
public DataSettingWebService()
{
this .fileName = this .Server .MapPath( @" /ClientBin/ServerData/UserMessage.xml " );
this .doc = new XmlDocument();
this .doc.Load(fileName);
}

 

 

添加元素

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
public bool CreateNewUser( string userName, string passWorld)
{
try {
if (userName == "" || passWorld == "" )
{
return false ;
}
XmlElement root
= doc.DocumentElement;

XmlElement newUser
= doc.CreateElement( " User " );

newUser.SetAttribute(
" username " , userName);
newUser.SetAttribute(
" passworld " , passWorld);
newUser.SetAttribute(
" abilitylevel " , " 0 " );
newUser.SetAttribute(
" registertime " , DateTime.Now.ToString());

for ( int i = 1 ; i <= 5 ; i ++ )
{
XmlElement newLevel
= doc.CreateElement( " Level " );
newLevel.SetAttribute(
" id " , i.ToString());
newLevel.SetAttribute(
" score " , " 0 " );
newLevel.SetAttribute(
" usetime " , " 0 " );
newLevel.SetAttribute(
" clicknum " , " 0 " );
newLevel.SetAttribute(
" playtime " , " 0 " );
newUser.AppendChild(newLevel);

}

root.AppendChild(newUser);
doc.Save(fileName);
return true ;
}
catch
{
return false ;
}
}

 

 

 

修改更新属性值

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
public bool UpdateUserGrade( string userName, int score, string useTime, string clickNum, int levelId)
{

bool IsAbilityLevelChange = false ;

XmlNodeList nodelist
= doc.GetElementsByTagName( " User " );

foreach (XmlNode xdu in nodelist)
{
if (xdu.Attributes[ " username " ].Value == userName)
{

XmlElement xeu
= xdu as XmlElement;
if (levelId > Convert.ToInt32(xeu.Attributes[ " abilitylevel " ].Value))
{
xeu.SetAttribute(
" abilitylevel " , levelId.ToString());
IsAbilityLevelChange
= true ;
}
nodelist
= xeu.GetElementsByTagName( " Level " );
foreach (XmlNode xdl in nodelist)
{
if (xdl.Attributes[ " id " ].Value == levelId.ToString())
{
if (score > Convert.ToInt32(xdl.Attributes[ " score " ].Value))
{
XmlElement xel
= xdl as XmlElement;
xel.SetAttribute(
" score " , score.ToString());
xel.SetAttribute(
" usetime " , useTime);
xel.SetAttribute(
" clicknum " , clickNum);
xel.SetAttribute(
" playtime " , DateTime.Now.ToString());
}

break ;
}

}
break ;
}

}
doc.Save(fileName);
return IsAbilityLevelChange;
}

 

 

 

转载于:https://www.cnblogs.com/hahacjh/archive/2010/03/11/1683765.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值