using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
public partial class TestTwo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadXml();
}
}
private void LoadXml()
{
XmlDocument xmlDoc = new XmlDocument();
string strXml =
@"<?xml version=""1.0"" encoding=""utf-16"" ?>
<projects>
<project id=""1"">p1</project>
<project id=""2"">
<name>p2</name>
</project>
</projects>";
xmlDoc.LoadXml(strXml);
Response.Write("<script>alert(' 原始:" + xmlDoc.OuterXml + "');</script>");//OuterXml是该结点包含的全部内容
//Response.Write(xmlDoc.OuterXml);//直接在浏览器中输出xml文档是空白,因为浏览器无法解析这些标签。
//根据属性值查询
XmlElement theProject = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("/projects/project[@id='1']");
Response.Write(theProject.InnerText+"<br/>");
//根据子节点值查询
XmlElement theProject2 = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("/projects/project[name='p2']");
Response.Write(theProject2.InnerText + "<br/>");//注意是查询到name那一层了。
//通过标签名查询,并修改
xmlDoc.GetElementsByTagName("project").Item(0).InnerText = "abcd";
Response.Write("<script>alert('修改第1个节点值为abcd:" + xmlDoc.OuterXml + "');</script>");
//增加属性
XmlElement theElement = xmlDoc.DocumentElement.FirstChild as XmlElement;
theElement.SetAttribute("no", "001");
Response.Write("<script>alert('增加属性no,001:" + xmlDoc.OuterXml + "');</script>");
//删除结点
theElement.ParentNode.RemoveChild(theProject);
Response.Write("<script>alert('删除第1个结点:" + xmlDoc.OuterXml + "');</script>");
//删除结点集
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/projects/project[@id<3]");
for (int i = 0; i < nodeList.Count; i++)
{
nodeList.Item(i).ParentNode.RemoveChild(nodeList.Item(i));
}
Response.Write("<script>alert('删除所有节点:" + xmlDoc.OuterXml + "');</script>");
}
}