zoukankan      html  css  js  c++  java
  • .NET:使用 XPATH 读取有 xmlns 属性的 XML 文档出现的问题

    问题

    xml

    1 <sqlMap namespace="WHTR.Dao.Accounts" xmlns="http://ibatis.apache.org/mapping"
    2   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    3 
    4 </sqlMap>

    这种带有 xmlns 属性的文档如果使用正常的 xpath 语法是获取不到元素或属性的。

    正确的代码

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.IO;
     7 using System.Xml;
     8 
     9 namespace CSharpStudy
    10 {
    11     class Program
    12     {
    13         static void Main(string[] args)
    14         {
    15             var xmlDocument = new XmlDocument();
    16             xmlDocument.Load(@"E:段光伟代码摇钱树PPmoney_NewLibrariesWHTR.DaoAccountsImplsSqlMapSuperviseAccount.xml");
    17             var nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
    18             nsmgr.AddNamespace("b", "http://ibatis.apache.org/mapping");
    19             var nodes = xmlDocument.SelectNodes("//b:select", nsmgr);
    20             foreach (XmlNode node in nodes)
    21             {
    22                 Console.WriteLine(node.Attributes["id"].Value.Split('.').Last());
    23             }
    24         }
    25     }
    26 }

    参考网站

    http://codeclimber.net.nz/archive/2008/01/09/How-to-query-a-XPath-doc-that-has-a-default.aspx

    http://stackoverflow.com/questions/2075773/xpath-for-xml-with-namespace

  • 相关阅读:
    P2480 SDOI 古代猪文(自带其他详细基础数论)
    01 分数规划
    P2606 ZJOI2010 排列计数
    P4140 奇数国
    SHOI 2014 概率充电器
    P2157 SDOI2009 学校食堂
    分块
    斜率 优化 dp
    线段树树状数组从入门到跳楼
    Ogre::scene_blend 场景混合
  • 原文地址:https://www.cnblogs.com/happyframework/p/3672400.html
Copyright © 2011-2022 走看看