回忆一个C#对XML的增删改查操作

好久不用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 = "p11";
            
//Response.Write("<script>alert('" + xmlDoc.OuterXml + "');</script>");

            
//增加属性
            XmlElement theElement = xmlDoc.DocumentElement.FirstChild as XmlElement;
            theElement.SetAttribute(
"no""001");
            
//Response.Write("<script>alert('" + xmlDoc.OuterXml + "');</script>");

            
//删除结点
            
//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>");
        }
    }
}

 

 

看到一位新手的笔记:

http://www.cnblogs.com/huazaizai/archive/2010/07/01/1769095.html

posted @ 2010-07-01 16:44  大气象  阅读(1591)  评论(6编辑  收藏  举报
http://www.tianqiweiqi.com