Write element to an XmlWriter in CSharp

Description

The following code shows how to write element to an XmlWriter.

Example


  /*from   w  w w . j a v a  2 s  .c  om*/
using System;
using System.Text;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;


public class MainClass
{
    public static void Main()
    {
        StringBuilder sb = new StringBuilder();
        XmlWriterSettings xws = new XmlWriterSettings();
        xws.OmitXmlDeclaration = true;
        xws.Indent = true;

        using (XmlWriter xw = XmlWriter.Create(sb, xws))
        {
            xw.WriteStartElement("Root");

            XElement child1 = new XElement("Child",
                new XElement("GrandChild", "some content")
            );
            child1.WriteTo(xw);

            XElement child2 = new XElement("AnotherChild",
                new XElement("GrandChild", "different content")
            );
            child2.WriteTo(xw);

            xw.WriteEndElement();
        }

        Console.WriteLine(sb.ToString());
    }
}




















Home »
  C# Tutorial »
    XML »




Load Parse
Document
Element
Attribute
Namespace
Query
Save
Schema
Style