Assuming a simple path, and you just want to add some data at the end of it.
Starting with some example data:
var xml = XDocument.Parse(@"<?xml version=""1.0""?>
<messages>
<request type=""MSG"">
<header>
<datestamp>2019-02-26T14:49:41+00:00</datestamp>
<source>1</source>
</header>
<body>
<title>Hi there</title>
</body>
</request>
</messages>
");
This won't work because the product node doesn't exist:
xml.XPathSelectElement("/messages/request/body/product")
?.Add(new XElement("description", "A new product"));
To do this you could define your own extension method:
public static class extensionMethods
{
public static XElement FindOrAddElement(this XContainer xml, string nodeName)
{
var node = xml.Descendants().FirstOrDefault(x => x.Name == nodeName);
if (node == null)
xml.Add(new XElement(nodeName));
return xml.Descendants().FirstOrDefault(x => x.Name == nodeName);
}
}
And chain these together to create your new path.
xml.FindOrAddElement("messages")
.FindOrAddElement("request")
.FindOrAddElement("body")
.FindOrAddElement("product")
?.Add(new XElement("description", "A new product"));
//element
is evaluated to an empty node set, where do you think the element should be created? – Tenderfoot