• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
人生之路,职业之路
读书使人充实,交谈使人机敏,写记使人精确;
“动因+兴趣”——决心-持之以恒-见效
博客园    首页    新随笔    联系   管理    订阅  订阅
C#中读取带有Xmlns命名空间的XML文件

XML文件格式如下:

<?xml version="1.0" encoding="utf-8"?>
<Resume xmlns="http://ns.test.com/resumes">
  <PersonalInformation>
    <GeneralInformation>
      <Name><![CDATA[张三]]></Name>
      <Birthday>1978-06</Birthday>
      <Gender>男</Gender>
    </GeneralInformation>

  </PersonalInformation>

</Resume>

由于这个XML文件加了Xmlns命名空间,如果直接用xxx.SelectSingleNode("PersonalInformation/GeneralInformation/Name"),结果返回null;

解决办法:

                XmlReaderSettings xs = new XmlReaderSettings();
                xs.XmlResolver = null;
                xs.ProhibitDtd = false;               
                XmlReader xr = XmlReader.Create(sourceFile, xs);
                XmlDocument doc = new XmlDocument();
                doc.Load(xr);//载入源XML文件

                XmlNamespaceManager nameSpace = new XmlNamespaceManager(doc.NameTable);
                nameSpace.AddNamespace("abc", "http://ns.test.com/resumes");
               

                XmlElement resume = doc.DocumentElement;

               //读取节点内容(要在节点前加命名空间前缀,如本例"abc:")

               resume.SelectSingleNode("abc:PersonalInformation/abc:GeneralInformation/abc:Name", nameSpace).InnerText.Trim()

posted on 2009-03-25 09:48  FreeBird  阅读(1717)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3