XML Attribute Setting

  • Thread starter Thread starter Dave
  • Start date Start date
D

Dave

I am trying to use the code below to set an attribute in my xml file. Below
is my code followed by the XML file:

xd.Load(XMLFileName)
xd.GetElementsByTagName("Setting3").Item(0).Attributes("Value").InnerText =
"303" 'Here is where I am getting an error
xd.Save(XMLFileName)
--------------------------------------------------------
<configuration>
<Section Name="Settings">
<Key Name="Setting1" Value="101"></Key>
<Key Name="Setting2" Value="202"></Key>
<Key Name="Setting3" Value="300"></Key>
<Key Name="Setting4" Value="404"></Key>
</Section>
</configuration>

Can anybody give me a hand on this one? Thanks,

-Dave
 
Why, o, why do you find it appropriate to ask a question about the reason
for an error an not bother to list the error message? What do you think we
are here - psychic???
 
My apologies Alex. The error message was:

An unhandled exception of type 'System.NullReferenceException' occurrred in
myapplication.exe
 
Dave, xd.GetElementsByTagName("Setting3") does return nothing
(NullReferenceException indeed). Because you have not tag Settings. You
must iterate through "Key" TagName collection (that you could take by
GetElementsByTagName("Key")) and find your Name="Setting3".

Best regards,
Sergey Bogdanov
http://www.sergeybogdanov.com
 
GetAttributesByName only looks one level deep. It will not get you nodes
that are grand-children or deeper. Even if it did, there is no node called
"settings3" - there is a "Key" node with the attribute "name" set to
"setting3"

What you want to use (if you don't care about making sure that the path
indeed exists) is

Dim el as XmlElement = xd("configuration")("Section")
For Each elSetting As XmlElement In el.ChildNodes
If elSetting.Attributes("Name").Value = "Setting3" Then
elSetting.Attributes("Value").Value = "303"
Exit For
End If
Next elSetting
 
Back
Top