0

I'm cloning an XML node from one XML to another n number of times. To identify each node i want to add an index attribute to it.

Here is the code is I use to Import node.

 XmlDocument template = new XmlDocument();
 template.Load(filelocation);
 XmlDocument Neweventlist= new XmlDocument();
 XmlNamespaceManager namespaces = new      XmlNamespaceManager(template.NameTable);

namespaces.AddNamespace("n", "http://www.hp.com/2009/software/opr/data_model");

XmlNode node = template.SelectSingleNode(".//n:event", namespaces);

Neweventlist.Load(eventlist_location);

    Neweventlist.DocumentElement.AppendChild(Neweventlist.ImportNode(template.DocumentElement, true));

Please help how i can set attribute for the new node that i'm adding.

Template document:

  <event>
 <server></server>
 </event>

output doc:

<eventlist>
<event index="0">
<server></server>
</event>
<event index="1">
<server></server>
</event>
<event index="2">
<server></server>
</event>
</eventlist>
5
  • Can you update your question with sample input XML document and expected output XML document? Commented Jul 30, 2015 at 10:37
  • @codeninja I have updated with the sample doc Commented Jul 30, 2015 at 10:53
  • @codeninja I'm able to append and iterate event node number of times i want but while appending using above code i want to set unique index attribute to each event node Commented Jul 30, 2015 at 10:55
  • the solution provided by karthik is good enough to solve your problem; if you still face any problem, let me know. Commented Jul 30, 2015 at 11:54
  • @codeninja yes the issue is resolved. Thank you! Commented Jul 30, 2015 at 11:59

1 Answer 1

1

Before adding the node to the Document,

XmlNode node = Neweventlist.ImportNode(template.DocumentElement, true); //Get the node
XmlAttribute attribute= Neweventlist.CreateAttribute("index"); // create attribute
attribute.Value = 0; //set the appropriate value
node.Attributes.Append(attribute); // add the attribute to node

Then add the node to the element,

Neweventlist.DocumentElement.AppendChild(node);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.