Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can append to xml

Tags:

c#

xml

i have this xml.

<project>
   <user>
      <id>1</id>
      <name>a</name>
   </user>
   <user>
      <id>2</id>
      <name>b</name>
  </user>
 </project>

now how can append a new element like this between element <project></project>

<user>
   <id>3</id>
   <name>c</name>
</user>
like image 651
Ma Eb Avatar asked Dec 27 '22 04:12

Ma Eb


2 Answers

string xml =
   @"<project>
        <user>
           <id>1</id>
           <name>a</name>
        </user>
        <user>
           <id>2</id>
           <name>b</name>
        </user>
     </project>";

XElement x = XElement.Load(new StringReader(xml));
x.Add(new XElement("user", new XElement("id",3),new XElement("name","c") ));
string newXml = x.ToString();
like image 82
L.B Avatar answered Jan 12 '23 20:01

L.B


If you mean using C# then probably the simplest way is to load the xml up into an XmlDocument object and then add a node representing the additional element.

e.g. something like:

string filePath = "original.xml";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
XmlElement root = xmlDoc.DocumentElement;

XmlNode nodeToAdd = doc.CreateElement(XmlNodeType.Element, "user", null);
XmlNode idNode = doc.CreateElement(XmlNodeType.Element, "id", null);
idNode.InnerText = "1";
XmlNode nameNode = doc.CreateElement(XmlNodeType.Element, "name", null);
nameNode.InnerText = "a";

nodeToAdd.AppendChild(idNode);
nodeToAdd.AppendChild(nameNode);


root.AppendChild(nodeToAdd);

xmlDoc.Save(filePath); // Overwrite or replace with new file name

But you haven't said where the xml fragments are - in files/strings?

like image 27
kaj Avatar answered Jan 12 '23 19:01

kaj