How to Add an Attribute to Node in C#
Knowing how to add an attribute to an element node in Microsoft Visual C# can make your XML application more user-friendly. C# is an object-oriented programming language used to develop web, mobile and desktop applications. Extensible Markup Language (XML) is basically a set of rules to encode documents to easily be shared with other programming languages. System.XML is a namespace that provides a set of classes in C# to write or edit XML data while it's in memory.
Instructions
-
-
1
Start Microsoft Visual C# Express and click "New Project..." on the left pane of your screen. Double-click "Windows Console Application."
-
2
Press "Ctrl" + "A" and press "Delete" to delete existing code. Copy and paste the following code to your "Program.cs" module to add a new attribute to a node:
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
XmlDocument myXMLDoc = new XmlDocument();
myXMLDoc.LoadXml("<book xmlns:bk='urn:samples' bk:ISBN='1-51111-57-5'>" +
"<title>Add Attribute to Node</title>" +
"</book>");
XmlElement myRoot = myXMLDoc.DocumentElement;
// Add a new attribute.
myRoot.SetAttribute("genre", "urn:samples", "Education");
Console.WriteLine("Modified XML:");
Console.WriteLine(myXMLDoc.InnerXml);
}
}
}
-
-
3
Press "F5" to run your program. The output will look like the following:
"Modified XML:
<book xmlns:bk="urn:samples" bk: ISBN="1-51111-57-5" bk:genre="Education"><title> Add Attribute to Node</title></book>"
-
1
References
- Photo Credit binary code digital tunnel background image by Stasys Eidiejus from Fotolia.com