Search code examples
c#xmllinq-to-xmlxelement

C# XElement - add element before value of existing element


I have an XML string like this:

<para>Some text in here</para>

and i need to add another element just after the opening para tag, so that it reads

<para><title>My Title</title>Some text in here</para>

I've tried this but it doesn't give me what i need:

content.Descendants("para") 
               .LastOrDefault()
               .Add(new XElement("title", "My Title"));

The problem with this is that it adds the <title> element and its contents to just before the closing <para> tag.

How can i get it where i want it please?


Solution

  • Try this

    string xml = "<para>Some text in here</para>";
                XElement para = XElement.Parse(xml);
    
                para.AddFirst(new XElement("title", "My Title"));