Add elements, attributes, and nodes to an XML tree (LINQ to XML)
You can add content (elements, attributes, comments, processing instructions, text, and CDATA) to an XML tree.
Methods for adding content
The following methods add child content to an XElement or an XDocument:
Method | Description |
---|---|
Add | Adds content at the end of the child content of the XContainer. |
AddFirst | Adds content at the beginning of the child content of the XContainer. |
The following methods add content as sibling nodes of an XNode. The most common node to which you add sibling content is XElement, although you can add valid sibling content to other types of nodes such as XText or XComment.
Method | Description |
---|---|
AddAfterSelf | Adds content after the XNode. |
AddBeforeSelf | Adds content before the XNode. |
Example: Create two XML trees and modify one of them
The following example creates two XML trees, and then modifies one of them.
var srcTree = new XElement("Root",
new XElement("Element1", 1),
new XElement("Element2", 2),
new XElement("Element3", 3),
new XElement("Element4", 4),
new XElement("Element5", 5)
);
var xmlTree = new XElement("Root",
new XElement("Child1", 1),
new XElement("Child2", 2),
new XElement("Child3", 3),
new XElement("Child4", 4),
new XElement("Child5", 5)
);
xmlTree.Add(new XElement("NewChild", "new content"));
xmlTree.Add(
from el in srcTree.Elements()
where (int)el > 3
select el
);
// Even though Child9 doesn't exist in srcTree, the following statement won't
// throw an exception, and nothing will be added to xmlTree.
xmlTree.Add(srcTree.Element("Child9"));
Console.WriteLine(xmlTree);
Dim srcTree As XElement =
<Root>
<Element1>1</Element1>
<Element2>2</Element2>
<Element3>3</Element3>
<Element4>4</Element4>
<Element5>5</Element5>
</Root>
Dim xmlTree As XElement =
<Root>
<Child1>1</Child1>
<Child2>2</Child2>
<Child3>3</Child3>
<Child4>4</Child4>
<Child5>5</Child5>
</Root>
xmlTree.Add(<NewChild>new content</NewChild>)
xmlTree.Add(
From el In srcTree.Elements()
Where CInt(el) > 3
Select el)
' Even though Child9 doesn't exist in srcTree, the following statement
' won't throw an exception, and nothing will be added to xmlTree.
xmlTree.Add(srcTree.Element("Child9"))
Console.WriteLine(xmlTree)
This example produces the following output:
<Root>
<Child1>1</Child1>
<Child2>2</Child2>
<Child3>3</Child3>
<Child4>4</Child4>
<Child5>5</Child5>
<NewChild>new content</NewChild>
<Element4>4</Element4>
<Element5>5</Element5>
</Root>
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for