Attribute create

In this chapter you will learn:

  1. How to create an attribute

Create an attribute

using System;/*from j a  v  a  2s  .  c o m*/
using System.Xml;

public class MainClass
{
  private static void Main(string[] args)
  {
    XmlDocument doc = new XmlDocument();
    XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
    doc.AppendChild(docNode);

    XmlNode productsNode = doc.CreateElement("products");
    doc.AppendChild(productsNode);

    XmlNode productNode = doc.CreateElement("product");
    XmlAttribute productAttribute = doc.CreateAttribute("id");
    productAttribute.Value = "1001";
    productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);

    XmlNode nameNode = doc.CreateElement("productName");
    nameNode.AppendChild(doc.CreateTextNode("Gourmet Coffee"));
    productNode.AppendChild(nameNode);
    XmlNode priceNode = doc.CreateElement("productPrice");
    priceNode.AppendChild(doc.CreateTextNode("0.99"));
    productNode.AppendChild(priceNode);


      // Save the document (to the Console window rather than a file).
    doc.Save(Console.Out);
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Adding a new comment node to the document
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