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()