XMLDOM - Add attribute to tag

  • Thread starter Thread starter D Ratcliffe
  • Start date Start date
D

D Ratcliffe

Hello

In a nutshell, I am looping through an XML document in a for loop, and
I want to insert a given value as an element to each tag as I go
along. i.e.:

for (int i=0; i < (rtnX.GetElementsByTagName("list").Count); i++) {

// I want here to add the attribute "display" to the selected tag
}

I have used the rtnX.DocumentElement.SetAttribute method, but this
seems to append my new attribute to my <root> tag, rather than each
<item> tag as it loops through. Here's an example of the XML if it
helps

WHAT I HAVE GOT:

<root>
<item id="1">Rita</item>
<item id="2">Bob</item>
<item id="3">Sue</item>
</root>

WHAT I WANT TO END UP WITH:

<root>
<item id="1" ADDEDVAL="XXX">Rita</item>
<item id="2" ADDEDVAL="XXX">Bob</item>
<item id="3" ADDEDVAL="XXX">Sue</item>
</root>

And as I say, prevously I used the .DocumentElement.SetAttribute
method but this just kept inserting the value into the <root>.

Any help would be much appreciated.

Regards

Darren
 
(e-mail address removed) (D Ratcliffe) wrote in
Hello

In a nutshell, I am looping through an XML document in a for loop, and
I want to insert a given value as an element to each tag as I go
along. i.e.:

for (int i=0; i < (rtnX.GetElementsByTagName("list").Count); i++) {

// I want here to add the attribute "display" to the selected tag
}

I have used the rtnX.DocumentElement.SetAttribute method, but this
seems to append my new attribute to my <root> tag, rather than each
<item> tag as it loops through. Here's an example of the XML if it
helps

WHAT I HAVE GOT:

<root>
<item id="1">Rita</item>
<item id="2">Bob</item>
<item id="3">Sue</item>
</root>

WHAT I WANT TO END UP WITH:

<root>
<item id="1" ADDEDVAL="XXX">Rita</item>
<item id="2" ADDEDVAL="XXX">Bob</item>
<item id="3" ADDEDVAL="XXX">Sue</item>
</root>

And as I say, prevously I used the .DocumentElement.SetAttribute
method but this just kept inserting the value into the <root>.

Any help would be much appreciated.

1) get a reference to the current node. It is wise to first select
the nodes in a nodelist and foreach through that nodelist.
2) create a new attribute by using rtnX.CreateAttribute();
3) add it to the Attributes collection of the current node using
the Append method of that collection.

FB
 
Back
Top