[C#] - Read XML โดยใช้ XmlTextReader

Standard
บทความนี้จะเป็นตัวอย่างการอ่านไฟล์ XML โดยใช้ C#
โดยไฟล์ที่ทดสอบจะอยู่ที่ c:\test.xml
ลองดูตัวอย่างจาก source code นะครับ



Source Code

using System.Xml;
try
            {
                XmlTextReader tReader = new XmlTextReader("C:\\test.xml");
                while (tReader.Read())
                {
                    XmlNodeType nType = tReader.NodeType;
                    switch (nType)
                    {
                        case XmlNodeType.Element:   // Start XML TAG
                            Console.WriteLine("=================== Start " + tReader.Name + " ====================");

                            if (tReader.HasAttributes)  // Atrributes
                            {
                                for (int i = 0; i < tReader.AttributeCount; i++)
                                {
                                    tReader.MoveToAttribute(i);
                                    Console.WriteLine("(Attr Name=" + tReader.Name + "  , Value=" + tReader.Value + ")");
                                }
                            }

                            break;
                        case XmlNodeType.Text:      // XML VALUE
                            Console.WriteLine("Data=" + tReader.Value);
                            break;

                        case XmlNodeType.EndElement: // End XML TAG
                            Console.WriteLine("=================== End " + tReader.Name + " ====================");
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }


XML
<?xml version="1.0"?>
<!--First Comment XmlTextWriter Sample Example-->
<!--myXmlFile.xml in root dir-->
<Student>
 <r:RECORD xmlns:r="urn:record">
  <Name>Student</Name>
  <Address>Colony</Address>
  <Char>arc</Char>
 </r:RECORD>
</Student>


ผลลัพธ์

=================== Start Student ====================
=================== Start r:RECORD ====================
(Attr Name=xmlns:r , Value=urn:record)
=================== Start Name ====================
Data=Student
=================== End Name ====================
=================== Start Address ====================
Data=Colony
=================== End Address ====================
=================== Start Char ====================
Data=arc
=================== End Char ====================
=================== End r:RECORD ====================
=================== End Student ====================