Element create

In this chapter you will learn:

  1. Create XML document by specifying the elements

Create XML document by specifying the elements

using System;/*  j  a va 2s  .c  om*/
using System.Collections;
using System.Data;
using System.Xml;

public class MainClass {
   public static void Main() {
      XmlDocument doc = new XmlDocument();

      XmlElement root = doc.CreateElement( "books" );
      doc.AppendChild( root );

      XmlElement eltBook = doc.CreateElement( "book" );
      root.AppendChild( eltBook );

      XmlElement eltTitle = doc.CreateElement( "title" );
      eltTitle.AppendChild( doc.CreateTextNode( "myTitle" ) );
      eltBook.AppendChild( eltTitle );

      XmlElement eltAuthor = doc.CreateElement( "author" );
      eltAuthor.AppendChild( doc.CreateTextNode(  "myAuthor" ) );
      eltBook.AppendChild( eltAuthor );

      XmlElement eltPrice = doc.CreateElement( "price" );
      eltPrice.AppendChild( doc.CreateTextNode(  "10.0" ) );
      eltBook.AppendChild( eltPrice );

      Console.WriteLine( doc.OuterXml );
   }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to create an attribute
Home » C# Tutorial » XML
Parse XML file
Parse XML String
Parse XML from URL
Element create
Attribute create
Comments create
XProcessingInstruction
XmlReader
Read double value from XML
XmlReader
XmlReaderSettings
XML formatter
XmlSerializer
XmlTextReader
XmlTextWriter
XmlWriter
XmlWriterSettings
Output XML to console