加载节点

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 LoadXML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xml = "<order id='001'>";
        xml +="<product>";
        xml +="<name>手机</name>";
        xml +="<quantity>10</quantity>";
        xml +="<price>2000</price>";
        xml +="</product>";
        xml += "</order>";
        XmlDocument xmlDoc = new XmlDocument();
        //使用变量xml中保存在XML字符串信息
        xmlDoc.LoadXml(xml);
        //显示根元素  使用Response对象的Write()方法输出  所以特殊标记需要使用实体引用
        string output="&lt;"+xmlDoc.DocumentElement.Name;
        output = "&nbsp;" + xmlDoc.DocumentElement.Attributes[0].Name + "=&quot;" + xmlDoc.DocumentElement.Attributes[0].Value + "&quot;&gt;";
        //获取根元素的第一个子元素<product>的所有子节点
        XmlNodeList nodes = xmlDoc.DocumentElement.FirstChild.ChildNodes;
        //output += "&lt;" + xmlDoc.GetElementsByTagName("order") + "&gt;";
        var node = xmlDoc.GetElementsByTagName("order");
        //output += "&lt;" + node.ParentNode.Name + "&gt;";

        for (int i = 0; i <node.Count; i++)
        {
            output += "&lt;" + node[i].Name;
            output +="&nbsp;"+node[i].Attributes[0].Name+"=&quot;"+node[i].Attributes[0].Value+"&quot;";
            output +="&gt;<br/>";
            for (var j = 0; j < node[i].ChildNodes.Count; j++)
            {
                output += "&nbsp;&nbsp;&nbsp;&nbsp;";
                output += "&lt;" + node[i].ChildNodes[j].Name + "&gt;";
                output += node[i].ChildNodes[j].ChildNodes[0].Value;
                output += "&lt;/" + node[i].ChildNodes[j].Name + "&gt;";
                output += "<br/>";
            }
            //output += "&lt;" + node.ChildNodes[i].FirstChild.ChildNodes[0].Name + "&gt;" + "<br/>";
            //output += "&lt;/" + node.ChildNodes[i].Name + "&gt;" + "<br/>";
        }
        Response.Write(output);
    }
}

posted @ 2012-04-22 20:27  微笑de『MY』  阅读(124)  评论(0编辑  收藏  举报