C# XML Example

 XML File: 
<BookList>  
     <Fiction>  
         <Title Genre="Adventure">Treasure Island</Title>  
         <Title Genre="Horror">It</Title>  
     </Fiction>  
     <NonFiction>  
         <Title Genre="Art Instruction">Fun With A Pencil</Title>  
         <Title Genre="Programming">OpenGL Programming Guide</Title>  
     </NonFiction>  
 </BookList>  

 C# Code: 
using System;
using System.Xml;

namespace XMLTest {
 class XMLParse {
  public static void Main () {
   XmlDocument xdBookList;

   xdBookList = new XmlDocument();
   xdBookList.Load("Test.XML");

   foreach (XmlNode xnTag in xdBookList.DocumentElement.ChildNodes) {
    Console.WriteLine("Found tag: " + xnTag.Name);

    foreach (XmlNode xnNested in xnTag.ChildNodes) {
     Console.WriteLine("  Found nested tag: " + xnNested.Name);
    }
   }

   XmlNodeList axnNodes;
   axnNodes = xdBookList.DocumentElement.SelectNodes("/BookList/Fiction/Title");

   foreach (XmlNode xnFiction in axnNodes) {
    Console.WriteLine("Found fiction title: " + xnFiction.InnerText);

    foreach (XmlAttribute xaAttrib in xnFiction.Attributes) {
     Console.WriteLine("  Includes attribute: " + xaAttrib.Name + " with value: " + xaAttrib.InnerText);
    }

    Console.WriteLine("  Genre is: " + xnFiction.Attributes["Genre"].InnerText);
   }
  }
 }
}

No comments:

Post a Comment