Link to home
Start Free TrialLog in
Avatar of pointeman
pointemanFlag for United States of America

asked on

Add Data to XML Sub-Root via C#?

Here's the XML tree. I need to add data to the "Links" node NOT the root.

<Settings>
    <Links>
    <Name>My Web Site</IpName>
    <Url>http://www.my.web.site.com/</IpUrl>
    </Links>
</Settings>

[Current code which alwayes writes to the Root]
 XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.Load(file);
 XmlElement root = xmlDoc.DocumentElement;
 XmlElement ele = xmlDoc.CreateElement("Name");
 XmlText txt = xmlDoc.CreateTextNode(txtName.Text);
 root.AppendChild(ele);
 root.LastChild.AppendChild(txt);
 xmlDoc.Save(file);

Avatar of geowrian
geowrian
Flag of United States of America image

You need to retrieve the "Links" node and then append "ele" and "txt" to to that (instead of the root). Without seeing how you are finding the root node, I'm not sure what would work best for you. That said, if you do:

XmlElement LinksElement = root.SelectSingleNode("Links");
LinksElement.AppendChild(ele); // replaces root.AppendChild(ele);
LinksElement.LastChild.AppendChild(txt); // replaces root.LastChild.AppendChild(txt);
Avatar of pointeman

ASKER

>>'finding root node'

A. XmlElement root = xmlDoc.DocumentElement; //default root of xml tree
Thanks. Then the lines of code I gave above should do the trick.
Yes, now the xml file looks like this:

<Settings>
    <Links>
       <Name>My Web Site</Name>
       <Url>http://www.my.web.site.com/</Url>
       <Name>Another Web</Name>
       <Url>www.another.web.com/</Url>
    </Links>
</Settings>

New Problem, cannot  read xml file as before, here's code:

ds = new DataSet();
ds.ReadXml(file);

List<KeyValuePair<string, string>> links = new List<KeyValuePair<string, string>>();

foreach (DataRow row in ds.Tables["Links"].Rows)
{
      links.Add(new KeyValuePair<string, string>(row["Name"].ToString(), row["Url"].ToString()));
}
ASKER CERTIFIED SOLUTION
Avatar of geowrian
geowrian
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yea, XML is not my forte. I would still like the new records to insert at a certain point in the xml file, not just simply appending. I would like a more orderly insert.