Modify XML attribute, how ?

maitung

New member
Joined
Nov 13, 2005
Messages
4
Programming Experience
Beginner
I have an xml file like below:
VB.NET:
<?xml version="1.0" encoding="utf-8" ?> 
<chessBoard columnNo="50" rowNo="50" DX="20" DY="20" Turn="X" >
	<item x="0" y="0" Value="X" />
	<item x="0" y="1" Value="O" />
	<item x="1" y="0" Value="X" />
	<item x="0" y="2" Value="O" />
	
</chessBoard>

I want to modify attributes of <chessBoard>, then loop through <item> and modify its attribute (Value) too, now what I do is just create a new xmldocument, copy (change some attribute, keep some) everything from the old file to the new then overite the old one, but I believe there's better way, reading and writing at the same time.
Plz help, tks.
 
first "Imports System.Xml"
VB.NET:
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] xmlfilename [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2] = [/SIZE][SIZE=2][COLOR=#800000]"text.xml"
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] xdoc [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] XmlDocument
xdoc.Load(xmlfilename)
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] root [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] XmlNode = xdoc.DocumentElement
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] attr [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] XmlAttribute = root.Attributes([/SIZE][SIZE=2][COLOR=#800000]"Turn"[/COLOR][/SIZE][SIZE=2])
[/SIZE][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][SIZE=2] attr.Value = [/SIZE][SIZE=2][COLOR=#800000]"X"[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Then
[/COLOR][/SIZE][SIZE=2]attr.Value = [/SIZE][SIZE=2][COLOR=#800000]"Y"
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Else
[/COLOR][/SIZE][SIZE=2]attr.Value = [/SIZE][SIZE=2][COLOR=#800000]"X"
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]End [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]If
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] items [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] XmlNodeList = root.SelectNodes([/SIZE][SIZE=2][COLOR=#800000]"item"[/COLOR][/SIZE][SIZE=2])
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] item [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] XmlNode
[/SIZE][SIZE=2][COLOR=#0000ff]For [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Each[/COLOR][/SIZE][SIZE=2] item [/SIZE][SIZE=2][COLOR=#0000ff]In[/COLOR][/SIZE][SIZE=2] items
item.Attributes([/SIZE][SIZE=2][COLOR=#800000]"Value"[/COLOR][/SIZE][SIZE=2]).Value = [/SIZE][SIZE=2][COLOR=#800000]"X"
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Next
[/COLOR][/SIZE][SIZE=2]xdoc.Save(xmlfilename)
[/SIZE]
 
Back
Top