对Xml文件中结点的搜索匹配

用SelectSingleNode()和SelectNodes()搜索结点
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();//建立文档对象
            try
            {
                doc.Load("http://www.cnblogs.com/myOrder.xml");
                XmlNode root = doc.DocumentElement;//获取文档的根节点
                XmlNode temp;
                temp = root.SelectSingleNode("姓名");
                Console.WriteLine("(查找1)" + temp);
                temp = root.SelectSingleNode("定购人信息/姓名");
                Console.WriteLine("(查找2)" + temp.Name+":"+temp.InnerText);
                temp = root.SelectSingleNode("订货信息/商品/品名");
                Console.WriteLine("(查找3)" + temp.Name + ":" + temp.InnerText);
                XmlNodeList templist = root.SelectNodes("订货信息/商品/品名");
                Console.WriteLine("(查找4)");
                foreach (XmlNode nodeinlist in templist)
                {
                    Console.WriteLine(nodeinlist.Name + ":" + nodeinlist.InnerText);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();//辅助代码,用于保留控制台窗口
        }
    }
}

在xml搜索节点(两种方法)
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();//建立文档对象
            try
            {
                doc.Load("http://www.cnblogs.com/myOrder.xml");
                //在xmlDocument对象中搜索元素
                Console.WriteLine("");
                XmlNodeList myNodeList = doc.GetElementsByTagName("品名");
                for (int i = 0; i < myNodeList;i++ )
                {
                    Console.WriteLine(myNodeList[i].Name+":"+myNodeList[i].InnerText);
                }
                //在xmlElement对象中搜索元素
                Console.WriteLine("在xmlElement对象中搜索元素");
                XmlElement myElement = doc.DocumentElement;
                myElement = (XmlElement)myElement.LastChild;
                myNodeList = myElement.GetElementsByTagName("品名");
                for (int i = 0; i < myNodeList; i++)
                {
                    Console.WriteLine(myNodeList[i].Name + ":" + myNodeList[i].InnerText);

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();//辅助代码,用于保留控制台窗口
        }
    }
}

转载于:https://www.cnblogs.com/guoguo11/archive/2009/06/04/1496174.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值