V
V
vladimirchelyabinskiy2016-04-17 09:10:01
C++ / C#
vladimirchelyabinskiy, 2016-04-17 09:10:01

c# how to add multiple elements to xml document?

private void button1_Click(object sender, EventArgs e)
        {
            var doc = XDocument.Load("test.xml");

            var pages = doc.Root.Element("pages");
            pages.Add(new XElement("p1", new XAttribute("name", textBox1.Text)));

            var pages2 = doc.Root.Element("p1");
            pages2.Add(new XElement("p2", new XAttribute("name2", textBox2.Text)));

            var pages3 = doc.Root.Element("p2");
            pages3.Add(new XElement("p3", new XAttribute("name3", textBox3.Text)));
            
            doc.Save("test.xml");
        }

An error occurs: Reference to an object, etc., etc....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VZVZ, 2016-04-17
@vladimirchelyabinskiy

Well, where will you get doc.Root.Element("p1") if you add it not to Root, but to pages?
This is how it should be done, I guess.

var pages = doc.Root.Element("pages");
var p1 = new XElement("p1", new XAttribute("name", textBox1.Text));
pages.Add(p1);

And then the same thing with p2...
And yet, doesn't doc have a CreateElement method?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question