C#中的XML分析器错误

本文关键字:错误 分析器 XML 中的 | 更新日期: 2023-09-27 17:58:33

我正在尝试创建一个函数来解析XML文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<list name="Grocery List" author="Ian" desc="Saturday grocery list">
        <item color="black" done="false">Milk</item>
        <item color="black" done="false">Eggs</item>
        <item color="blue" done="false">Water</item>
</list>

它正确地解析了属性,但未能返回列表项的值。以下是它使用的函数和类:

class List
{
    public string[] listItems;
    public string[] colorArray;
    public string[] doneArray;
    public string listName;
    public string listAuthor;
    public string listDesc;
    public string err;       
}

阅读器定义:

class ListReader
{
    public List doListParse(string filename)
    {
         List l = new List();
         int arrayCount = 0;
         try
         {
             XmlReader r = XmlReader.Create(filename);
             while (r.Read())
             {
                 if (r.NodeType == XmlNodeType.Element && r.Name == "list")
                 {
                     //Get the attributes of the list
                     l.listName = r.GetAttribute("name");
                     l.listAuthor = r.GetAttribute("author");
                     l.listDesc = r.GetAttribute("desc");
                     while (r.NodeType != XmlNodeType.EndElement)
                     {
                         r.Read();
                         if (r.Name == "item")
                         {
                             r.Read();
                             if (r.NodeType == XmlNodeType.Text)
                             {
                                 //Get The Attributes
                                 l.colorArray[arrayCount] = r.GetAttribute("color");
                                 l.doneArray[arrayCount] = r.GetAttribute("done");
                                 //Get The Content
                                 l.listItems[arrayCount] = r.Value.ToString();
                                 arrayCount++;
                             }
                             r.Read();
                         }
                     }
                 }
             }
         }
         catch (Exception e)
         {
             l.err = e.ToString();
         }
         return l;
    }
}

当我执行程序时,它会给出以下异常:

System.NullReferenceException:对象引用未设置为对象的实例。

这是怎么回事?

C#中的XML分析器错误

我建议您使用序列化程序。XmlSerializer级相当不错。它将简化您的代码。

因此,首先定义将映射到此XML结构的模型:

[XmlRoot("list")]
public class GroceryList
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("author")]
    public string Author { get; set; }
    [XmlAttribute("desc")]
    public string Description { get; set; }
    [XmlElement("item")]
    public Item[] Items { get; set; }
}
public class Item
{
    [XmlAttribute("color")]
    public string Color { get; set; }
    [XmlAttribute("done")]
    public bool Done { get; set; }
    [XmlText]
    public string Value { get; set; }
}

然后简单地反序列化XML:

class Program
{
    static void Main()
    {
        var serializer = new XmlSerializer(typeof(GroceryList));
        using (var reader = XmlReader.Create("groceriesList.xml"))
        {
            var list = (GroceryList)serializer.Deserialize(reader);
            // you could access the list items here
        }
    }
}

您可以使用Linq To Xml。

var xElem = XDocument.Parse(xml).Element("list"); //or XDocument.Load(filename)
var list = new
            {
                Name = xElem.Attribute("name").Value,
                Author = xElem.Attribute("author").Value,
                Desc = xElem.Attribute("desc").Value,
                Items = xElem.Elements("item")
                            .Select(e => new{
                                Color = e.Attribute("color").Value,
                                Done = (bool)e.Attribute("done"),
                                Value = e.Value,
                            })
                            .ToList()
            };