Free Information Technology Magazines and eBooks

Thursday, October 09, 2008

VB .NET: Inserting and Removing XML Attribute

When working on Database to XML conversion projects, I usually uses .NET Framework's XSD.exe to create VB or C# classes and later use XmlSerializer to generate XML file from the class. Using this method, I don't have a direct control on the generated attributes. For example, serializer automatically generate this attribute:
"xmlns:xsd=http://www.w3.org/2001/XMLSchema-instance"
What if I don't want that? or I want to add new attributes aside from the auto generated values. To demonstrate on how to add and remove attributes, here is a sample code in VB .NET

Imports System.Xml.Serialization
Imports System.Xml
Imports System.IO

Dim
o As New Gateway
o.Name = "Test Name"
o.Age = 18

Dim serializer As New XmlSerializer(GetType(Gateway))
Dim memory As New IO.MemoryStream()
Try
serializer.Serialize(memory, o)
memory.Position = 0
Dim doc As New XmlDocument
doc.Load(memory)

'Add Attribute
Dim attribute As XmlAttribute
attribute = doc.CreateAttribute("xsi", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance")
attribute.Value = "/apps/export.xsd"

'Remove an attribute
doc.DocumentElement.RemoveAttribute("xmlns:xsd")
doc.DocumentElement.SetAttributeNode(attribute)
doc.Save(txtSourceDIR.Text & "\" & .ReferenceNo & ".xml")
MessageBox.Show("Convertion was successfully completed!")
Catch ex As Exception
MessageBox.Show("Error in convertion : " & ex.Message)
End Try
memory.Close()


On this example, I added new attribute xsi:noNamespaceSchemaLocation="apps/export.xsd"
Also I removed an existing generated attribute xmlns:xsd

Thats It!... Hope this help other developer out there... Godspeed...


0 comments: