Solved

VS C# Writing XML

Posted on 2015-01-17
6
135 Views
Last Modified: 2015-01-18
I have just begun looking into how to write an xml file using visual studio c#. I came across this sample code and I can see I need to define 'book' someplace.  How do I correct this code to define the proper structure for book? It has the Title, Author.Name, Publisher, Price attributes.

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = ("    ");
            settings.CloseOutput = true;
            settings.OmitXmlDeclaration = true;
            using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
            {
                writer.WriteStartElement("book");
                writer.WriteElementString("title", book.Title);
                writer.WriteElementString("author", book.Author.Name);
                writer.WriteElementString("publisher", book.Publisher);
                writer.WriteElementString("price", book.Price.ToString());
                writer.WriteEndElement();
                writer.Flush();
0
Comment
Question by:rwheeler23
  • 3
  • 2
6 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40555807
It would help if you showed the XML structure you are trying to achieve.
0
 

Author Comment

by:rwheeler23
ID: 40555828
My apologies. Here it is:

<?xml version="1.0" encoding="utf-8" ?>
<!-- Books.xml stores information about Mahesh Chand and related books -->
<books>
  <book ISBN="9831123212" yearpublished="2002">
    <title>A Programmer's Guide to ADO.NET using C#</title>
    <author>
      <first-name>Mahesh</first-name>
      <last-name>Chand</last-name>
    </author>
    <publisher>Apress</publisher>
    <price>44.99</price>
  </book>
</books>
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 40555835
Honestly, I would consider using XML serialization for this task. I wrote a couple of articles on the subject some time back, complete with terrible jokes:

http://www.experts-exchange.com/Programming/Languages/.NET/A_3024-Introduction-to-XML-Serialization-in-NET.html
http://www.experts-exchange.com/Programming/Languages/.NET/A_3041-Writing-a-Class-Struct-to-be-XML-Serialized-and-Creating-a-Class-from-a-Schema.html

With serialization, you already have your C# structure, and you just dump it out to XML into the intended structure, typically with minimal changes to the C# code.

However, to answer the question you asked:

using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
{
    writer.WriteStartElement("books");
    writer.WriteStartElement("book");
    writer.WriteStartAttribute("ISBN");
    writer.WriteValue(book.ISBN);
    writer.WriteEndAttribute();
    writer.WriteElementString("title", book.Title);
    writer.WriteStartElement("author");
    writer.WriteStartElement("first-name");
    writer.WriteValue(book.Author.Name);
    writer.WriteEndElement();
    writer.WriteElementString("publisher", book.Publisher);
    writer.WriteElementString("price", book.Price.ToString());
    writer.WriteEndElement();
    writer.WriteEndElement();
    writer.Flush();
}

Open in new window


Any time you call WriteStartElement, you have to, at some point, call WriteEndElement; where you do so depends on what you are trying to output in terms of the XML. (The same goes for WriteStartAttribute.) In the above, I call a WriteStartElement for "books", and at the end of the whole thing I call a corresponding WriteEndElement. The reason? I want the stuff in between to be a part of the <books> element that is output, so I don't want to "close" the <books> element before I write all of the other stuff.

You don't need an "WriteEnd***" call for the WriteElementString calls--they are more or less self-closing.

The above code generated:

Screenshot
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Closing Comment

by:rwheeler23
ID: 40556360
Excellent. Thank you.
0
 
LVL 20

Expert Comment

by:Daniel Van Der Werken
ID: 40556373
Kaufmed's answer is the correct answer. However, I wonder if your actual question is more basic. You need a class or structure defined that has the object you want, right?

I came across this sample code and I can see I need to define 'book' someplace.  How do I correct this code to define the proper structure for book? It has the Title, Author.Name, Publisher, Price attributes.

First, you need to create your classes:
    public class Author
    {
        public struct AuthorName
        {
            [XmlElement("first-name")]
            public string First_Name;
            [XmlElement("last-name")]
            public string Last_Name;
        };

        private AuthorName name = new AuthorName();
        public AuthorName Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public Author(string first, string last)
        {
            name = new AuthorName();
            name.First_Name = first;
            name.Last_Name = last;
        }

    }

    public class Book
    {
        public string Title { get; set; }
        public string Publisher { get; set; }
        public decimal Price { get; set; }
        public Author Author { get; set; }
        public string ISBN { get; set; }
        public string Year_Published { get; set; }
    }

Open in new window


Next, the code to write this is almost exactly like kaufmed's solution:

       
public void doIt()
        {
            Book book = new Book();
            book.Title = "A Programmer's Guide to ADO.NET using C#";
            book.Price = 44.99M;
            book.Publisher = "Apress";
            book.Author = new Author("Mahesh", "Chanad");
            book.ISBN = "9831123212";
            book.Year_Published = "2002";

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = ("    ");
            settings.CloseOutput = true;
            settings.OmitXmlDeclaration = true;
            using (XmlWriter writer = XmlWriter.Create(@"C:\books.xml", settings))
            {
                writer.WriteStartElement("books");
                writer.WriteStartElement("book");
                writer.WriteAttributeString("ISBN", book.ISBN);
                writer.WriteAttributeString("Year-Published", book.Year_Published);
                writer.WriteElementString("title", book.Title);
                writer.WriteStartElement("author");
                writer.WriteElementString("first-name", book.Author.Name.First_Name);
                writer.WriteElementString("last-name", book.Author.Name.Last_Name);
                writer.WriteEndElement();
                writer.WriteElementString("publisher", book.Publisher);
                writer.WriteElementString("price", book.Price.ToString());
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.Flush();

            }
        }

Open in new window


Here's the actual output from this code:

<books>
    <book ISBN="9831123212" Year-Published="2002">
        <title>A Programmer's Guide to ADO.NET using C#</title>
        <author>
            <first-name>Mahesh</first-name>
            <last-name>Chanad</last-name>
        </author>
        <publisher>Apress</publisher>
        <price>44.99</price>
    </book>
</books>

Open in new window

0
 

Author Comment

by:rwheeler23
ID: 40556384
That though dawned on me as I working on some other code. I continue to be impressed by the knowledge that is shared on this website. Thanks to all of you my code gets cleaner and more efficient with each application.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

948 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now