How to add to 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 <project></project> add a new element like this between the <project></project> element

 <user> <id>3</id> <name>c</name> </user> 
+4
source share
3 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(); 
+6
source

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

eg. sort of:

 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 did not say where the xml fragments are in files / lines?

+3
source

If you have the following XML file:

 <CATALOG> <CD> <TITLE> ... </TITLE> <ARTIST> ... </ARTIST> <YEAR> ... </YEAR> </CD> </CATALOG> 

and you need to add another <CD> node with all its child nodes:

 using System.Xml; //use the xml library in C# XmlDocument document = new XmlDocument(); //creating XML document document.Load(@"pathOfXmlFile"); //load the xml file contents into the newly created document XmlNode root = document.DocumentElement; //points to the root element (catalog) XmlElement cd = document.CreateElement("CD"); // create a new node (CD) XmlElement title = document.CreateElement("TITLE"); title.InnerXML = " ... "; //fill-in the title value cd.AppendChild(title); // append title to cd XmlElement artist = document.CreateElement("ARTIST"); artist.InnerXML = " ... "; cd.AppendChild(artist); XmlElement year = document.CreateElement("YEAR"); year.InnerXML = " ... "; cd.AppendChild(year); root.AppendChild(cd); // append cd to the root (catalog) document.save(@"savePath");//save the document 
+1
source

Source: https://habr.com/ru/post/1399590/


All Articles