梁某人

发展才是硬道理

导航

解决了XMLTextReader的用法的一个难题,EndElement

如下,CodeGuru或者CodeProject上找到的例子都没有处理 像这样的情形 :
<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();
            }

posted on 2006-03-15 18:43  涛仔28  阅读(958)  评论(0编辑  收藏  举报