In the previous blog, I've demonstrated how to add a node or an XML element to an existing document. In this blog, I'll introduce two ways to add an attribute to an existing node.
The first way we will use the SetAttributeNode method of the DocumentElement object to add an XMLAttribute as seen below:
Dim objDocument As New XmlDocument
objDocument.LoadXml("<Cars><Make>Toyota</Make></Cars>")
Dim objAttribute1 As XmlAttribute
objAttribute1 = objDocument.CreateAttribute("Type")
objAttribute1.InnerText = "Foreign"
objDocument.DocumentElement.SetAttributeNode(objAttribute1)
The second way is to add an attribute is to call the Append method of the Attributes collection class:
Dim objAttribute2 as XmlAttribute
objAttribute2 = objDocument.CreateAttribute("Body")
objAttribute2.Value = "Sedan"
objDocument.DocumentElement.FirstChild.Attributes.Append(objAttribute2)
and finally we can show the output to the textbox with the statement:
txtOutput.Text = objDocument.InnerXml
In the end, if you run these two code blocks together, your output should look something like this:
<Cars Type="Foreign"><Make Body="Sedan">Toyota</Make></Cars>
Wednesday, May 30, 2007
Adding Attributes To An Existing XML Document
Labels:
System.XML,
Tips,
Tricks,
Tutorial,
VB.net,
Visual Basic.net,
xml
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment