0

So... I have 2 textboxes and 1 button. And when I input data to those textboxes, and click the button, I would like it to enter xml file and add new element with attributes to it, without replacing it. After a lot of browsing I managed to do something that replaced all text in my xml file, or I got an error, so I decided to post a question here.

So this is how my xml file looks:

<library>
<book name="Her way" price="20"></book>
<book name="His way" price="20"></book>
</library>

and what I'm trying to do is to insert:

<book name="Their way" price="22"></book>

bellow last one so it would look like:

<library>
<book name="Her way" price="20"></book>
<book name="His way" price="20"></book>
<book name="Their way" price="22"></book>
</library>

And every time I click button again, it adds it same way, ofc I would change name and price in textbox.

I came up with this code, but I am fairly new to xml so I don't know how to modify it or make it work.

XDocument doc = XDocument.Load("booklibrary.xml");
            doc.Add(new XElement("book",
            new XAttribute("name", textBox1.Text),
            new XAttribute("price", textBox3.Text)));
            doc.Save("booklibrary.xml");

Thank you!

1
  • 1
    What does your current code doing? Does it throw an error? If so, post it Commented Sep 6, 2012 at 18:13

2 Answers 2

1

Don't use XDocument if you aren't working with namespaces. Just use an XElement and your code will work:

var library = XElement.Load("booklibrary.xml");
library.Add(new XElement("book",
new XAttribute("name", textBox1.Text),
new XAttribute("price", textBox3.Text)));
library.Save("booklibrary.xml");

Because you used XDocument, Add tried to add the new element next to the root element <library> instead of inside it, causing an exception because there can be only one root element. Several illustrative examples can be found on MSDN.

By using XElement as shown above, this problem is fixed.

Sign up to request clarification or add additional context in comments.

Comments

0

I would use LINQ to XML instead, very easy to use and tons of functionality!:

XElement ele = XElement.Load("booklibrary.xml");
            ele.Element("library").Add(
                new XElement("book",
                             new XAttribute("name", textBox1.Text),
                             new XAttribute("price", textBox3.Text)));
ele.Save();

This is much cleaner, and it uses the new .NET stuff.

1 Comment

he's using LINQ to XML already. Although using XElement is better than using XDocument.

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.