2

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

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

在此处输入图像描述 请在下面查看我的代码,并告知我哪里做得不对。或者有没有更好的方法来实现这一点?您的意见和建议将不胜感激。

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>
4

2 回答 2

3

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

if (childNode.Attributes != null)
{
   foreach(XmlAttribute attrib in childNode.Attributes)
   {
    ...
   }
}
于 2012-06-15T05:35:42.710 回答
0

您需要确保 childNode.Attributes 具有值,因此在前面添加 if 语句

if (childNode.Attributes != null)
{
    foreach(XmlAttribute attrib in childNode.Attributes) 
于 2012-06-15T05:35:16.377 回答