Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

VS C# Writing XML

Posted on 2015-01-17
6
Medium Priority
?
154 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

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…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

618 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