0

How to to write .xml file with this string?

string:

string string1 = textbox1.text;
string string2 = textbox2.text;
string string3 = textbox3.text;
string string4 = textbox4.text;

the xml file result:

<?xml version="1.0" encoding="utf-8" ?>
        <books>
            <book Title="Pure JavaScript" Price=string1/>
            <book Title="Effective C++" Price=string2/>
            <book Title="Assembly Language: Step-By-Step" Price=string3/>
            <book Title="Oracle PL/SQL Best Practices" Price=string4/>
        </books>
2
  • You have 8 different strings in your code sample and because of the default naming we have no idea what each means. It is difficult to see how these are supposed to match up with your XML. Commented Dec 12, 2011 at 19:08
  • The XML is also not valid, as the Price attributes do not have quotes around the values. Commented Dec 12, 2011 at 19:14

3 Answers 3

3

You can use Linq to XML for this. Suppose you have a class Book:

class Book
{
    public string Title { get; set; }
    public decimal Price { get; set; }
}

And now you have a list of books that you want to put into an XML document:

List<Book> books = new List<Book>();
books.Add(new Book() { Title = "Pure JavaScript", Price = 59.0M});

XDocument xdoc = new XDocument(new XElement("books", books.Select( x=> new XElement("book", 
                               new XAttribute("Title", x.Title), 
                               new XAttribute("Price", x.Price)))));

Now you can just save this XDocument:

xdoc.Save("text.xml");

This produces:

<books>
  <book Title="Pure JavaScript" Price="59.0" />
</books>
Sign up to request clarification or add additional context in comments.

2 Comments

sorry, but for create a two <book Title="Pure JavaScript" Price="59.0" /> ?
Just add another book to the collection: books.Add(new Book() { Title = "Some other book name", Price = 11.99M});
0

Check out the System.Xml namespace. Particularly XmlDocument and XmlNode

Also XML Literals (I know VB has them, not sure about C#)

1 Comment

C# doesn't have XML Literals.
0

Look at these keywords:

  1. XmlWriter
  2. XDocument
  3. XmlDocument
  4. Serialization

I think, in your situation XmlWriter is the best choice.

3 Comments

-1 for recommending XmlTextWriter, which should no longer be used directly.
@JohnSaunders, ok, XmlWriter. And where did I recommend to use it directly?
You mentioned it. Why mention it in a list of things to use?

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.