zoukankan      html  css  js  c++  java
  • xmlDoc.SelectNodes用法(获取不到节点时注意事项)

    注:以下举例仅针对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;

            private XmlDocument xmlDoc;
            protected void Button1_Click(object sender, EventArgs e)
            {
                LoadXml();

    ————申明xml命名空间管理对象
                XmlNamespaceManager m = new XmlNamespaceManager(xmlDoc.NameTable);   

    ————添加命名空间 
                m.AddNamespace("fuck", "http://www.google.com/schemas/sitemap/0.84");       

    ————注意用法,原本路径是“urlset/url”,须改写为“/fuck:urlset/fuck:url”,依此类推。
                XmlNodeList nodelist = xmlDoc.SelectNodes("/fuck:urlset/fuck:url",m);         


                if (nodelist == null)
                {
                    Page.RegisterStartupScript("", "alert('列表是空的!')");
                }
                else
                {
                    foreach (XmlNode node in nodelist)
                    {
                        if (node["priority"].InnerText == "0.4")
                        {
                            node["priority"].InnerText = "0.8";
                        }
                    }
                    xmlDoc.Save(Server.MapPath("XML/test2.xml"));
                }
            }
            private void LoadXml()
            {
                xmlDoc = new XmlDocument();
                xmlDoc.Load(Server.MapPath("XML/test1.xml"));
            }

    下面是我的xml文件——

    ———这个xmlns属性值就是xml自定义的命名空间!上面命名空间的值就是根据这里来写的!

       <urlset xmlns="http://www.google.com/schemas/sitemap/0.84">      
    <url>
       <loc>http://www.baidu.com/</loc>
       <lastmod>2013-12-05</lastmod>
       <changefreq>daily</changefreq>
       <priority>0.5</priority>
       </url>
    -  <url>
       <loc>http://www.baidu.com/Default.htm</loc>
       <lastmod>2013-12-05</lastmod>
       <changefreq>weekly</changefreq>
       <priority>0.4</priority>
       </url>
    </urlset>

    当使用xmldocument.selectnodes()时,如果xml文件中有自定义的命名空间的话(也就是根节点属性值),在使用selectnodes()函数时,一定要记得增加命名空间

    关于这一点,官网上也有说明:

    Remarks


    XPath expressions can include namespaces. Namespace resolution is supported using the XmlNamespaceManager. If the XPath expression includes a prefix, the prefix and namespace URI pair must be added to the XmlNamespaceManager.

    在此附上官网链接,说的很详细,还有例子。XmlNode.SelectNodes Method (String, XmlNamespaceManager)

  • 相关阅读:
    [原创]ASP.NET MVC调用美图秀秀开放平台拼图实现
    使用Lucene检索文档中的关键字
    Unitils+hibernate+Spring+PostgreSql做dao层测试遇到的错误
    初探IronJS
    IntelliJ IDEA 12 创建Web项目 教程 超详细版
    百度面试题:求绝对值最小的数
    jquery+css实现简单的评分功能
    Knockot JS 数字输入插件
    Diagnostic Policy Service 服务处于起不来
    WCF学习笔记(一) 之 开门见山
  • 原文地址:https://www.cnblogs.com/mooncher/p/3461603.html
Copyright © 2011-2022 走看看