A Simple XML Example : XmlDocument « XML « C# / C Sharp






A Simple XML Example

   

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
public class MainClass {
    public static void Main() {
        XmlElement xmlBook;
        XmlAttribute xmlParticipantType;
        XmlElement xmlFirstName;
        XmlElement xmlLastName;

        XmlDocument xmlDoc = new XmlDocument();
        XmlElement xmlBooks = xmlDoc.CreateElement("Books");
        xmlDoc.AppendChild(xmlBooks);

        xmlBook = xmlDoc.CreateElement("Book");

        xmlParticipantType = xmlDoc.CreateAttribute("type");
        xmlParticipantType.InnerText = "Author";
        xmlBook.Attributes.Append(xmlParticipantType);

        xmlFirstName = xmlDoc.CreateElement("FirstName");
        xmlFirstName.InnerText = "J";
        xmlBook.AppendChild(xmlFirstName);

        xmlLastName = xmlDoc.CreateElement("LastName");
        xmlLastName.InnerText = "R";
        xmlBook.AppendChild(xmlLastName);

        xmlBooks.AppendChild(xmlBook);

        xmlBook = xmlDoc.CreateElement("Book");

        xmlParticipantType = xmlDoc.CreateAttribute("type");
        xmlParticipantType.InnerText = "Author";
        xmlBook.Attributes.Append(xmlParticipantType);

        xmlFirstName = xmlDoc.CreateElement("FirstName");
        xmlFirstName.InnerText = "E";
        xmlBook.AppendChild(xmlFirstName);

        xmlLastName = xmlDoc.CreateElement("LastName");
        xmlLastName.InnerText = "B";
        xmlBook.AppendChild(xmlLastName);

        xmlBooks.AppendChild(xmlBook);

        XmlNodeList authorsList = xmlDoc.SelectNodes("Books/Book[@type=\"Author\"]");

        foreach (XmlNode node in authorsList) {
            XmlNode firstName = node.SelectSingleNode("FirstName");
            XmlNode lastName = node.SelectSingleNode("LastName");
            Console.WriteLine("{0} {1}", firstName, lastName);
        }
    }
}

   
    
  








Related examples in the same category

1.LoadXml
2.Save, AppendChild, CreateXmlDeclaration, CreateElement
3.Call GetElementsByTagName to get an element
4.Use Load method in XmlDocument to load xml document
5.Use SelectNodes to query nodes by XPath
6.Get XML Nodes in a Specific XML Namespace
7.Find Elements with an XPath Search
8.Add XmlElement
9.Load With Includes
10.Non CData Normalize