您的位置:首页 > 其它

LinQ to XML——LinQ to XML操作XML文档

2011-03-28 11:15 295 查看
使用XDocument对象的Element方法,获取制定层次结构中指定一个元素的值
publicvoidMyDocElement()
{

XDocumentxdoc=XDocument.Load(Server.MapPath("hamlet.xml"));
//查找地址的元素
Response.Write(xdoc.Element("PLAY").Element("TITLE").Value+"<br/>");
//如果包含多个同名元素,则只返回第一个元素
Response.Write(xdoc.Element("PLAY").Element("PERSONAE").Element("PERSONA").Value+"<br/>");

}

用SetValue方法去修改指定元素的值
publicvoidMyDocElementSetValue()
{
XDocumentxdoc=XDocument.Load(Server.MapPath("hamlet.xml"));
//修改指定位置元素的值
xdoc.Element("PLAY").Element("PERSONAE").Element("PERSONA").SetValue("冯瑞涛");
//如果包含多个同名元素,则只返回第一个元素
Response.Write(xdoc.Element("PLAY").Element("PERSONAE").Element("PERSONA").Value+"<br/>");
}

使用Add方法添加制定元素到指定位置
publicvoidMyDocElementAdd()
{
XDocumentxdoc=XDocument.Load(Server.MapPath("hamlet.xml"));
//定义一个演员
XElementxe=newXElement("PERSONA","冯瑞涛");
//将演员添加到指定元素的最后面
xdoc.Element("PLAY").Element("PERSONAE").Add(xe);

//重新查询结果
varquery=frompeopleinxdoc.Descendants("PERSONA")
selectpeople.Value;
//people是符合条件元素结果集而people.Value;就是这个结果集的所有元素的值的序列
Response.Write(query.Count()+"个演员被找到。");

Response.Write("<p/>他们是:<p/>");

foreach(variteminquery)
{
//输出他们的值
Response.Write(item+"<br/>");

}

}

使用Remove方法删除制定元素
publicvoidMyDocElementRemove()
{
XDocumentxdoc=XDocument.Load(Server.MapPath("hamlet.xml"));
//删除
xdoc.Element("PLAY").Element("PERSONAE").Element("PERSONA").Remove();

//重新查询结果编程了25个演员
varquery=frompeopleinxdoc.Descendants("PERSONA")
selectpeople.Value;
//people是符合条件元素结果集而people.Value;就是这个结果集的所有元素的值的序列
Response.Write(query.Count()+"个演员被找到。");

Response.Write("<p/>他们是:<p/>");

foreach(variteminquery)
{
//输出他们的值
Response.Write(item+"<br/>");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: