C#中的XML分析器错误

时间:2013-02-09 15:23:39

标签: c# xml xml-parsing

我正在尝试创建一个解析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:未将对象引用设置为对象的实例。

这里发生了什么?

2 个答案:

答案 0 :(得分:5)

我建议您使用序列化程序。 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
        }
    }
}

答案 1 :(得分:0)

您可以使用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()
            };