Gmac
Gmac

Reputation: 169

Assign attribute names and add subchilds

Trying to figure out how to add attribute names and more nodes. Code so far:

'Create the xmlDoc with Views root
Dim doc As New XmlDocument
doc.LoadXml("<Views></Views>")

'Add a View element
Dim vElem As XmlElement = doc.CreateElement("View")
vElem.InnerXml = "Name"
vElem.InnerText = "vACCESS"
doc.DocumentElement.AppendChild(vElem)

'Set writer settings
Dim sett As New XmlWriterSettings
sett.Indent = True

'Save file and indent
Dim sw As XmlWriter = XmlWriter.Create("d:\input\data.xml", sett)
doc.Save(sw)

I'm getting this:

<?xml version="1.0" encoding="utf-8"?>
<Views>
    <View>vACCESS</View>
</Views>

But what I want is this:

<?xml version="1.0" encoding="utf-8"?>
<Views Code="Sample1">
    <View Name="vACCESS">
        <Criteria>ACCESS</CRITERIA>
    </View>
</Views>

Upvotes: 0

Views: 30

Answers (1)

Tony Hinkle
Tony Hinkle

Reputation: 4742

To add the attribute on the <Views> element, you need to get a handle to it as an element. Once you have an element, you just use element.SetAttribute("Name", "Value").

'Create the xmlDoc with Views root
Dim doc As New XmlDocument
doc.LoadXml("<Views></Views>")

'Enumerate the root element and add the attribute
Dim rElem As XmlElement = doc.FirstChild
rElem.SetAttribute("Code", "Sample1")

'Add a View element and attribute
Dim vElem As XmlElement = doc.CreateElement("View")
vElem.SetAttribute("Name", "vACCESS")

Dim cElem As XmlElement = doc.CreateElement("Criteria")
cElem.InnerText = "ACCESS"

vElem.AppendChild(cElem)

doc.DocumentElement.AppendChild(vElem)

'Set writer settings
Dim sett As New XmlWriterSettings
sett.Indent = True

'Save file And indent
Dim sw As XmlWriter = XmlWriter.Create("c:\temp\data.xml", sett)
doc.Save(sw)

Upvotes: 1

Related Questions