Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

inserting elements to an existing node in XML using c#

Status
Not open for further replies.

Sniipe

Programmer
Joined
Oct 9, 2006
Messages
115
Location
IE
I'm not sure if this is the best place to post, but perhaps you can help me.

I have an xml document which has a node/element (are they the same thing?) which is currently just <userinputs />.

I want add multiple elements to that element like so
<userinputs>
<input question="Name" answer="John" />
<input question="Age" answer="17" />
<input question="Sex" answer="Male" />
</userinputs>

I assume I have to do a foreach loop to get to the element userinputs then I have to do another loop for each item in the arraylist and at every itteration I must create a new element and add it to the userinputs element...
 
BTW, the xml document looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<system>
<base>
<header>
...
</header>
<userinputs />
<power />
</base>
</system

So getting there is an issue for me at the moment.

this code won't work for me
foreach(XmlNode xNode in xDoc)
{
if(xNode.Name == "userinputs")
{//do stuff}
}
 
This is just one way of doing it.
Code:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(/*your xml here*/);
XmlNode userInputsNode = xmlDoc.SelectSingleNode("system/base/userinputs");
foreach(/*your objecthere*/ in /*your ArrayList here*/)
{                
    XmlNode nodeToAdd = xmlDoc.CreateNode(XmlNodeType.Element, "input", string.Empty);
    XmlAttribute questionAttribute = xmlDoc.CreateAttribute("question");
    questionAttribute.Value = //In here goes the question string;
    nodeToAdd.Attributes.Append(questionAttribute);
    XmlAttribute answerAttribute = xmlDoc.CreateAttribute("answer");
    answerAttribute.Value = //In here goes the answer string;
    nodeToAdd.Attributes.Append(answerAttribute);
    userInputsNode.AppendChild(nodeToAdd);
}
O.B.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top