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()
轉載于:https://www.cnblogs.com/chenhailong/p/6368612.html
總結
以上是生活随笔為你收集整理的C#中读取带有Xmlns命名空间的XML文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于OnPaint、FormPaint会
- 下一篇: MySQL5.7.17绿色版安装