Link to home
Start Free TrialLog in
Avatar of Abdu_Allah
Abdu_Allah

asked on

Append node to XML file?

How can I add the following node:
<user>
     <name> xxx </name>
     <id>1</id>
     <mark A="10" B="20" />
</user>


To the following XML file using XMLDocument or XMLwriterText:

<users>
     <user>
         <name> yyy</name>
          <id>1</id>
          <mark A="11" B="12" />
     </user>
     <user>
           <name> zzz</name>
           <id>2</id>
           <mark A="34" B="50" />
     </user>
</users>
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

You could use something like:

            XmlDocument doc = new XmlDocument();
            doc.Load("C:\\test.xml");

            XmlNode user = doc.CreateElement("user");
            user.AppendChild(doc.CreateElement("name")).InnerText = "xxx";
            user.AppendChild(doc.CreateElement("id")).InnerText = "1";

            XmlNode mark = doc.CreateElement("mark");
            mark.Attributes.SetNamedItem(doc.CreateAttribute("A")).InnerText = "10";
            mark.Attributes.SetNamedItem(doc.CreateAttribute("B")).InnerText = "20";

            user.AppendChild(mark);
            doc.FirstChild.AppendChild(user);

            doc.Save("C:\\test2.xml");
Avatar of Abdu_Allah
Abdu_Allah

ASKER

Whay I got the following error:
System.InvalidOperationException: The current node cannot contain other nodes
Source Error:
Line 126:     doc.FirstChild.AppendChild(user)

 
What does the XML you are appending to look like in full ? Is there a Schema or DTD associated with it ?
No schema no DTD
What does your full XML look like ?
Here is the full file:

<?xml version="1.0" encoding="utf-8"?>
<users>
     <user>
         <name> yyy</name>
          <id>1</id>
          <mark A="11" B="12" />
     </user>
     <user>
           <name> zzz</name>
           <id>2</id>
           <mark A="34" B="50" />
     </user>
</users>
Try it with just the snippet you posted before and see if that works.
Same error.
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland 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
Many thanks