问题地址:http://bbs.csdn.net/topics/390547532?page=1#post-395294391
XML格式如下:
<?xml version="1.0" standalone="yes"?> <ExportDsSetup xmlns="http://tempuri.org/ExportDsSetup.xsd"> <Line> <LineName>LINE2</LineName> <SetupName>WB00971</SetupName> <ProductName /> <Machine> <MachineName>HF</MachineName> <MachineType>HF</MachineType> <MachineNr>1</MachineNr> </Machine> </Line> </ExportDsSetup>
public static bool ParseXML(string strPath) { XmlDocument dom = new XmlDocument(); dom.Load(strPath);//装载XML文档 //遍历所有节点 foreach (XmlElement item in dom.DocumentElement.ChildNodes) { string lineName = item.SelectSingleNode("Line/LineName").InnerText; //返回的结果一直为Null 原因是xml文档中使用了命名空间 } return true; }
解决方法是
追加
XmlNamespaceManager nsMgr = newXmlNamespaceManager(dom.NameTable);nsMgr.AddNamespace("ns", "http://tempuri.org/ExportDsSetup.xsd");
完全方法:
XmlDocument dom = newXmlDocument(); dom.Load(@"XMLFile1.xml");//装载XML文档 //遍历所有节点 XmlNamespaceManager nsMgr = newXmlNamespaceManager(dom.NameTable); nsMgr.AddNamespace("ns", "http://tempuri.org/ExportDsSetup.xsd"); XmlNodeList xnl =dom.SelectNodes("//ns:ExportDsSetup//ns:Line", nsMgr); foreach (XmlNode node in xnl) { string lineName =node.SelectSingleNode("//ns:LineName", nsMgr).InnerText; }
方法二:
XmlDocument dom = new XmlDocument(); dom.Load(@"XMLFile1.xml"); XmlNamespaceManager nsMgr = new XmlNamespaceManager(dom.NameTable); nsMgr.AddNamespace("ns", "http://tempuri.org/ExportDsSetup.xsd"); foreach (XmlElement item in dom.DocumentElement.ChildNodes) { string lineName = item.SelectSingleNode("//ns:ExportDsSetup//ns:Line//ns:LineName", nsMgr).InnerText; 剩下的依次取值 }