XML参考 :XmlReader 详解、实例(3) 读取XML节点和属性名称

.NET Framework 类库

XmlReader 类

 

表示提供对 XML 数据进行快速、非缓存、只进访问的读取器,即 对 XML 数据流的只进只读访问。XmlReader 类符合 W3C 可扩展标记语言 (XML) 1.0 和“XML 中的命名空间”建议。

三.读取XML节点和属性名称

class XmlReaderDemo
    
{
        
private static string xmlFilePath = @"..\..\EmployeeInfo.xml";// @"D:\\EmployeeInfo.xml"

        
public static string ReadXml()
        
{
            
string result = "";
            
try
            
{
                
using (XmlReader reader = XmlReader.Create(xmlFilePath))
                
{
                    
while (reader.Read())
                    
{
                        
if (reader.NodeType == XmlNodeType.Element)
                        
{
                            
for (int count = 0; count < reader.Depth; count++)
                            
{
                                result 
+= "";
                            }

                            result 
+= "->" + reader.Name;
                            
if (reader.HasAttributes)
                            
{
                                result 
+= "(";
                                
for (int count = 0; count < reader.AttributeCount; count++)
                                
{
                                    reader.MoveToAttribute(count);
                                    result 
+= reader.Name + ",";
                                }

                                result 
+= ")";
                            }

                            result 
+= "\n";
                        }

                    }

                }

            }

            
catch (Exception ex)
            
{
                result 
+= "An Exception occured: " + ex.Message;
            }

            
return result;
        }

    }


    
class Program
    
{
        
static void Main()
        
{
            
string strReturn = XmlReaderDemo.ReadXml();
            Console.WriteLine(strReturn);
            Console.ReadLine();
        }

    }

效果图如下所示:

原文地址:https://www.cnblogs.com/Dlonghow/p/1254290.html