0

I came so far, but how do I add an XElement in the third place instead of first place?

I have to add it to 2 big files.

protected void Button1_Click(object sender, EventArgs e)
{
    var xml = XElement.Load(Server.MapPath(map1));
    var noprovider = xml.Elements("Component").Where(d => !d.Elements("L").Any());
    var prov in noprovider)
    {
        prov.AddFirst(new XElement("L", ""));
    }
    xml.Save(Server.MapPath(map1));
}

The XML

<Reservedele>
    <Component>
        <Type>Støvsuger</Type>
        <Art>yiryidryi</Art>
        <Bemærkning> adadgadg</Bemærkning>
        <Varenummer>dfgdfg</Varenummer>
        <OprettetAf>John</OprettetAf>
        <Date>28. januar 2017</Date>
    </Component>
</Reservedele>

3 Answers 3

4

I am not sure to understand your question. Do you mean something like that?

using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace XmlTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var xmlText = @"
<Reservedele>
  <Component>
    <Type>Støvsuger</Type>
    <Art>yiryidryi</Art>
    <Bemærkning> adadgadg</Bemærkning>
    <Varenummer>dfgdfg</Varenummer>
    <OprettetAf>John</OprettetAf>
    <Date>28. januar 2017</Date>
  </Component>
</Reservedele>";

            using (var sr = new StringReader(xmlText))
            {
                var xml = XElement.Load(sr);
                var noprovider = xml.Elements("Component").Where(d => !d.Elements("L").Any());

                noprovider.Elements().ElementAt(1).AddAfterSelf(new XElement("L", ""));
                //noprovider.Elements("Art").First().AddAfterSelf(new XElement("L", ""));

                Console.WriteLine(xml.ToString());
            }

            Console.WriteLine("\nPress any key ...");
            Console.ReadKey();
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@TheNewone if the answer is correct, please consider marking it as Accepted
0

Check XmlNode.InsertAfter and XmlNode.InsertBefore methods. Visit https://msdn.microsoft.com/en-us/library/system.xml.xmlnode.insertbefore(v=vs.110).aspx

Comments

-2

I would suggest you to use

        System.Xml.XmlDocument myDoc = new System.Xml.XmlDocument();

        try
        {
            myDoc.Load(XMLFullFileName);
        }
        catch (Exception e)
        {
            throw new Exception("Loading failed!", e);
        }

Then you can iterate myDoc with all its children and elements and append or insert as you wish. Have a look at XmlDocument-Class

1 Comment

Switching from XDocument to XmlDocument is unnecessary and doesn't provide any benefits. Also, you aren't answering the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.