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
Solved

VS C# Writing XML

Posted on 2015-01-17
6
137 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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Video Player 2017 5 35
VB.NET (2008) - Refactoring Question 2 23
performance tune IIS 10 on win 2016 that only runs one website 4 118
List<PaisEntity> - show some 1 28
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

809 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