我正在编写一个xml阅读器,其中类结构将表示来自xml文件的数据..
举个例子:
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
如何找到节点包含子节点!我使用了isempty元素方法!但我得到了例外。
public element read(XmlReader xml)
{
element elem = new element();
while (xml.Read())
{
if (xml.IsEmptyElement)
{
elem.ElemName = xml.Name;
if (xml.HasAttributes)
{
for (int i = 0; i <= xml.AttributeCount; i++)
{
xml.MoveToNextAttribute();
attribute attrib = new attribute();
attrib.AttName = xml.Name;
attrib.AttValue = xml.Value;
elem.Attributes.Add(attrib);
}
}
return elem;
}
else
{
elem.ElemName = xml.Name;
if (xml.HasAttributes)
{
for (int i = 1; i < xml.AttributeCount; i++)
{
xml.MoveToNextAttribute();
attribute attrib = new attribute();
attrib.AttName = xml.Name;
attrib.AttValue = xml.Value;
elem.Attributes.Add(attrib);
}
}
elem.subElems.Add(read(xml)); -> Object reference not set to an instance of an object.
return elem;
}
}
return elem;
}
我使用两个班级。一个叫做元素,一个叫做属性。我在这里做的是逐行,当我找到一个元素时,我创建了一个元素类型对象。然后我检查该元素是否包含任何属性。如果是这样,我为我遇到的属性创建属性类型对象,并将它们添加到元素对象中的属性列表中。然后我检查子元素,如果找到任何子元素,我将它们作为单独的元素对象添加到主元素对象的列表中。
class element
{
private String elemName;
public String ElemName
{
get { return elemName; }
set { elemName = value; }
}
private String elemValue;
public String ElemValue
{
get { return elemValue; }
set { elemValue = value; }
}
private List<attribute> attributes;
internal List<attribute> Attributes
{
get { return attributes; }
set { attributes = value; }
}
private List<element> SubElems;
internal List<element> subElems
{
get { return SubElems; }
set { SubElems = value; }
}
}
class attribute
{
private String Name;
public String AttName
{
get { return Name; }
set { Name = value; }
}
private String value;
public String AttValue
{
get { return this.value; }
set { this.value = value; }
}
}
答案 0 :(得分:2)
创建element elem = new element();
时,您永远不会将值分配给subElems
,只会分配给elem.ElemName = xml.Name
。因此,您得到NullReferenceException
因为在subElems上,您在创建对象后拥有null
。我重构了你的代码(请注意,我对element
class)
public element read(XmlReader xml)
{
element elem = new element();
while (xml.Read())
{
elem.ElemName = xml.Name;
if (xml.HasAttributes)
{
for (int i = 0; i <= xml.AttributeCount; i++)
{
xml.MoveToNextAttribute();
attribute attrib = new attribute();
attrib.AttName = xml.Name;
attrib.AttValue = xml.Value;
elem.Attributes.Add(attrib);
}
}
if (xml.IsEmptyElement)
{
return elem;
}
else
{
elem.subElems = new List<element>(); //create new List of subelements
elem.subElems.Add(read(xml));
return elem;
}
}
return elem;
在element
初始化subElems
和Attributes
的构造函数中定义
public element()
{
this.subElems = new List<element>();
this.Attributes = new List<attribute>();
}
将您的字段声明更改为
private List<element> SubElems = new List<element>();
private List<attribute> attributes = new List<attribute>();