C#操作XML报Object reference not set to an instance of an object

问题地址: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;
剩下的依次取值

            }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值