执行xpath时提示,需要命名空间管理器或XsltContext。此查询具有前缀、变量或用户定义的函数

来源:互联网 发布:lol冰狼辅助源码 编辑:程序博客网 时间:2024/05/02 01:31

执行xpath时提示,需要命名空间管理器或XsltContext。此查询具有前缀、变量或用户定义的函数  

2012-05-05 10:45:48|  分类:默认分类 |  标签:要命名空间管理器  xsltcontext  此查询具有前缀  |举报|字号 订阅

如果 XPath 表达式包含前缀,则必须将前缀和命名空间 URI 对添加到 XmlNamespaceManager 中。 
 XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

例子:

   xml文件内容:

<?xml version="1.0"?>
       <roots weight="3" xmlns:sml="www.sdkd.net.cn">
            <sml:root leaf="a">1111</sml:root>
            <sml:root leaf="b">2222</sml:root>
            <sml:root leaf="c">3333</sml:root>
            <sml:root leaf="de">3333</sml:root>
            <sml:root leaf="d">4444</sml:root>
            <sml:root leaf="e">5555</sml:root>
            <sml:root leaf="f">6666</sml:root>
           <sml:root leaf="g">7777</sml:root>
           <sml:root leaf="h">8888</sml:root>
           <sml:root leaf="i">9999</sml:root>
           <sml:root leaf="j">0000</sml:root>
  </roots>

程序:

     XmlDocument doc = new XmlDocument();
            doc.Load("a.xml");
           XmlNode root = doc.DocumentElement;

     XmlNamespaceManager nsp = new XmlNamespaceManager(doc.NameTable);
            nsp.AddNamespace("sml", "www.sdkd.net.cn");
            XmlNodeList a = root.SelectNodes("child::sml:root[starts-with(@leaf,'d')]",nsp);
            Console.WriteLine("Find " + a.Count.ToString());
            foreach (XmlNode e in a)
            {
                Console.WriteLine(e.InnerText);
            
            }

以上程序中使用到了sml前缀,因此需要添加命名空间管理

XmlNamespaceManager 类包含命名空间 URI 及其前缀的集合。它允许解析、添加和移除集合中的命名空间。某些上下文需要此类以提高 XML 处理性能。例如,XsltContext 类使用 XmlNamespaceManager 以支持 XPath。

0 0
原创粉丝点击