好久不用XML了。最近做Silverlight項目,需要通過Web Service通路一些C++的Dll.
使用XML傳遞資料。正好複習一下XML操作。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISPrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdsATOfd3bkFGazxCMx8VesATMfhHLlN3XnxCMwEzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-YWan5CNzUGN1MTN3YmMiBDM5kjZxYTMzMjZ3cjYiNTZ4Y2Yw8CX5AzLchDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjL4M3Lc9CX6MHc0RHaiojIsJye.gif)
大氣象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;
namespace HCLoad.Web
{
public partial class TestXml : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
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);
//根據子節點值查詢
XmlElement theProject2 = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("/projects/project[name='p2']");
Response.Write(theProject2.InnerText);//注意是查詢到name那一層了。
//通過标簽名查詢,并修改
xmlDoc.GetElementsByTagName("project").Item(0).InnerText = "p11";
//Response.Write("<script>alert('" + xmlDoc.OuterXml + "');</script>");
//增加屬性
XmlElement theElement = xmlDoc.DocumentElement.FirstChild as XmlElement;
theElement.SetAttribute("no", "001");
//删除結點
//theElement.ParentNode.RemoveChild(theProject);
//删除結點集
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>");
}
}
看到一位新手的筆記: