【问题标题】:How To Check if an Object is Instantiated?如何检查对象是否被实例化?
【发布时间】:2012-06-15 05:27:45
【问题描述】:

我正在尝试将 xml 的所有元素和属性列出到两个单独的 List 对象中。

我能够获取 xml 中的所有元素。
但是当我尝试添加获取每个元素内所有属性的功能时,我总是遇到System.NullReferenceException: Object reference not set to an instance of an object.

请在下面查看我的代码,并告知我哪里做得不对。或者有没有更好的方法来做到这一点?您的 cmets 和建议将不胜感激。

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace TestGetElementsAndAttributes
{
    public partial class MainForm : Form
    {
        List<string> _elementsCollection = new List<string>();
        List<string> _attributeCollection = new List<string>();

        public MainForm()
        {
            InitializeComponent();

            XmlDataDocument xmldoc = new XmlDataDocument();
            FileStream fs = new FileStream(@"C:\Test.xml", FileMode.Open, FileAccess.Read);
            xmldoc.Load(fs);

            XmlNode xmlnode = xmldoc.ChildNodes[1];

            AddNode(xmlnode);
        }

        private void AddNode(XmlNode inXmlNode)
        {
            try
            {
                if(inXmlNode.HasChildNodes)
                {
                    foreach (XmlNode childNode in inXmlNode.ChildNodes)
                    {
                        foreach(XmlAttribute attrib in childNode.Attributes)
                        {
                            _attributeCollection.Add(attrib.Name);
                        }

                        AddNode(childNode);
                    }
                }
                else
                {
                    _elementsCollection.Add(inXmlNode.ParentNode.Name);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.GetBaseException().ToString());
            }
        }
    }
}

同时发布示例 XML。

<?xml version="1.0" encoding="UTF-8" ?> 
<DocumentName1>
    <Product>
        <Material_Number>21004903</Material_Number> 
        <Description lang="EN">LYNX GIFT MUSIC 2012 1X3 UNITS</Description> 
        <Packaging_Material type="25">457</Packaging_Material> 
    </Product>
</DocumentName1>

【问题讨论】:

  • 确保您在 childNode.Attributes 中有值不确定是否有问题,但 21004903 似乎没有属性
  • 使用调试器找出什么变量为空。
  • (别忘了关闭你的 FileStream...)
  • 我尝试在 foreach 之前先使用 childNode.Attributes.Count &gt; 0if(chaildNode !=null) 进行检查。但它总是进入循环,即使节点没有Attributes
  • @yonan2236 - 属性可以为空(请参阅我的回答)我猜该行为符合 XML DOM 规范

标签: c# xml winforms .net-2.0


【解决方案1】:

您应该使用以下内容检查childNode.Attributes 的存在:

if (childNode.Attributes != null)
{
   foreach(XmlAttribute attrib in childNode.Attributes)
   {
    ...
   }
}

【讨论】:

  • 太棒了!我没有想到这个:)。我的检查是if (childNode != null)
【解决方案2】:

你需要确保 childNode.Attributes 有值,所以在前面添加 if 语句

if (childNode.Attributes != null)
{
    foreach(XmlAttribute attrib in childNode.Attributes) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2015-08-03
    相关资源
    最近更新 更多