您的位置:首页 > 其它

.net中xml基本操作

2009-02-04 10:26 302 查看
Code

一.添加数据:

public bool AddArticle(string NewsTitle, string NewsContent, string NewsClassID)

{

XmlDocument doc = new XmlDocument();

doc.Load(HttpContext.Current.Server.MapPath(articlePath)); //装载文章xml

int newID = 1;

if (doc.DocumentElement.SelectSingleNode("//Article[@ID]") != null)

{ //最后一个文章ID+1就是新的文章ID

newID = Convert.ToInt32(doc.DocumentElement.SelectSingleNode("//Article[last()]").Attributes["ID"].Value) + 1;

}

XmlElement el = doc.CreateElement("Article");

XmlAttribute id = doc.CreateAttribute("ID");

id.Value = newID.ToString();

XmlAttribute title = doc.CreateAttribute("Title");

title.Value = NewsTitle;

XmlAttribute date = doc.CreateAttribute("Date");

date.Value = DateTime.Now.ToString();

XmlAttribute classID = doc.CreateAttribute("ClassID");

classID.Value = NewsClassID;

XmlCDataSection content = doc.CreateCDataSection(NewsContent);

el.Attributes.Append(id);

el.Attributes.Append(title);

el.Attributes.Append(classID);

el.Attributes.Append(date);

el.AppendChild(content);

doc.DocumentElement.AppendChild(el);

doc.Save(HttpContext.Current.Server.MapPath(articlePath));

return true;

}

二.修改数据

public bool EditArticle(string NewsTitle, string NewsContent, string NewsID)

{

try

{

XmlDocument document = new XmlDocument();

document.Load(HttpContext.Current.Server.MapPath(this.articlePath));

XmlNode node = document.DocumentElement.SelectSingleNode("Article[@ID=" + NewsID + "]");

if (node != null)

{

node.Attributes["Title"].Value = NewsTitle;

node.FirstChild.Value = NewsContent;

}

document.Save(HttpContext.Current.Server.MapPath(this.articlePath));

return true;

}

catch

{

return false;

}

}

三.删除数据

public bool DeleteArticle(string NewsID)

{

bool flag = false;

try

{

XmlDocument document = new XmlDocument();

document.Load(HttpContext.Current.Server.MapPath(this.articlePath));

XmlNode oldChild = document.DocumentElement.SelectSingleNode("Article[@ID=" + NewsID + "]");

if (oldChild != null)

{

oldChild.ParentNode.RemoveChild(oldChild);

}

document.Save(HttpContext.Current.Server.MapPath(this.articlePath));

}

catch

{

flag = false;

}

return flag;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: