<a name="test" /> 就是没有 </a>标签的情形,这时候处理a元素是不会碰到 EndElement的。
这里做了一个处理,即判断其深度。
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(streamReader);
startDocument(); //开始分析
int dept = -1;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Hashtable attributes = new Hashtable();
string strURI = reader.NamespaceURI;
string strName = reader.Name;
if (reader.HasAttributes)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
attributes.Add(reader.Name, reader.Value);
}
}
startElement(strURI, strName, strName, attributes);
if(dept != -1 && reader.Depth <= dept) //处理 "/>"的标签
endElement(string.Empty, reader.Name, string.Empty);
dept = reader.Depth;
break;
case XmlNodeType.EndElement:
endElement(string.Empty, reader.Name, string.Empty);
break;
case XmlNodeType.Text:
characters(reader.Value);
break;
default:
break;
}
}
return (Namespace) objectStack.Pop();
}
catch (XmlException e)
{
Console.WriteLine("error occured: " + e.Message);
}
finally
{
if(reader != null) reader.Close();
}
try
{
reader = new XmlTextReader(streamReader);
startDocument(); //开始分析
int dept = -1;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Hashtable attributes = new Hashtable();
string strURI = reader.NamespaceURI;
string strName = reader.Name;
if (reader.HasAttributes)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
attributes.Add(reader.Name, reader.Value);
}
}
startElement(strURI, strName, strName, attributes);
if(dept != -1 && reader.Depth <= dept) //处理 "/>"的标签
endElement(string.Empty, reader.Name, string.Empty);
dept = reader.Depth;
break;
case XmlNodeType.EndElement:
endElement(string.Empty, reader.Name, string.Empty);
break;
case XmlNodeType.Text:
characters(reader.Value);
break;
default:
break;
}
}
return (Namespace) objectStack.Pop();
}
catch (XmlException e)
{
Console.WriteLine("error occured: " + e.Message);
}
finally
{
if(reader != null) reader.Close();
}