Solved

VS C# Writing XML

Posted on 2015-01-17
6
130 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 74

Expert Comment

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

Author Comment

by:rwheeler23
Comment Utility
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 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Closing Comment

by:rwheeler23
Comment Utility
Excellent. Thank you.
0
 
LVL 19

Expert Comment

by:Daniel Van Der Werken
Comment Utility
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
Comment Utility
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
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…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

771 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

9 Experts available now in Live!

Get 1:1 Help Now