I have the following code that inserts a new element and its attributes into
an xml file. The problem is the syntax of the inserted row. here is my code:
'Create an XmlDataDocument.
Dim doc As XmlDataDocument = New XmlDataDocument
'Load the schema.
doc.DataSet.ReadXmlSchema("c:\animal.xsd")
Dim dtAnimals As DataTable = doc.DataSet.Tables.Item("animal")
'Load the XML data.
Dim reader As XmlTextReader = New XmlTextReader("c:\animal.xml")
doc.Load(reader)
reader.Close()
Dim root As XmlNode = doc.DocumentElement
' Create new animal element
Dim animalElement As XmlElement = doc.CreateElement("animal")
root.AppendChild(animalElement)
' Set animal attributes (type, name, age)
Dim typeAttribute As XmlAttribute = doc.CreateAttribute("type")
typeAttribute.InnerText = "dog"
animalElement.SetAttributeNode(typeAttribute)
Dim nameAttribute As XmlAttribute = doc.CreateAttribute("name")
nameAttribute.InnerText = "snoopy"
animalElement.SetAttributeNode(nameAttribute)
Dim ageAttribute As XmlAttribute = doc.CreateAttribute("age")
ageAttribute.InnerText = "10"
animalElement.SetAttributeNode(ageAttribute)
'Save File
doc.Save("c:\animal.xml")
The above code gives mr the following xml file, notice the closing animal
tag in the second row:
<?xml version="1.0"?>
<root>
<animal type="cat" name="garfield" age="3" />
<animal type="dog" name="snoopy" age="10"></animal>
</root>
I need my xml file to look like this:
<?xml version="1.0"?>
<root>
<animal type="cat" name="garfield" age="3" />
<animal type="dog" name="snoopy" age="10" />
</root>
Any ideas how I can accomplish this? I would perfer to use the
xmlDataDocument object as I will also have comments in the xml file that will
need to stay, and will most likly be displaying the xml file in a datagrid.