好久不用XML了。最近做Silverlight項目,需要通過Web Service訪問一些C++的Dll.
使用XML傳遞數據。正好復習一下XML操作。
大氣象
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 =