CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: XML Reading

  1. #1
    Join Date
    Jul 2011
    Posts
    2

    XML Reading

    Hey guys

    I've been trying to use XmlTextReader for this one but could not manage to get exactly what I wanted.
    I have this XML (example). I'd like to read each of it's elements and attributes into textBoxes.
    but... only from the firstCatalog. how do I do it?


    <?xml version="1.0"?>
    <store>
    <firstCatalog>
    <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
    <description>An in-depth look at creating applications
    with XML.</description>
    </book>
    <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-12-16</publish_date>
    <description>A former architect battles corporate zombies,
    an evil sorceress, and her own childhood to become queen
    of the world.</description>
    </book>
    </firstCatalog>
    <secondCatalog>
    <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-11-17</publish_date>
    <description>After the collapse of a nanotechnology
    society in England, the young survivors lay the
    foundation for a new society.</description>
    </book>
    <book id="bk104">
    <author>Corets, Eva</author>
    <title>Oberon's Legacy</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-03-10</publish_date>
    <description>In post-apocalypse England, the mysterious
    agent known only as Oberon helps to create a new life
    for the inhabitants of London. Sequel to Maeve
    Ascendant.</description>
    </book>
    </secondCatalog>
    </store>




    cheers

  2. #2
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: XML Reading

    Quick little reading xml sample...

    Code:
                XmlDocument doc = new XmlDocument();
                doc.Load(@"your.xml");
    
                if (doc.HasChildNodes)
                {
                      XmlNode catalogNode = doc.SelectSingleNode("store/firstCatalog");
    
                      // use catalogNode to select child nodes and retrieve info about books etc.
                      // for example...
                      XmlNodeList books = catalogNode.SelectNodes("book");
                }
    (If I have a syntax err or anything I apologize... not testing, just typing it here... but the process is sound.)

  3. #3
    Join Date
    Jul 2011
    Posts
    2

    Re: XML Reading

    worked lovely using Item(i)

    thanks

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: XML Reading

    Another way is to not work with xml as an xml reader exercise, but rather take an OO approach.

    In other words, turn the xml into class objects and work with the classes like you would with other C# classes (i.e. as OO).

    To do this, create a few classes that represent the xml schema. These classes look like any other C# classes, but just contain a few xml markup attributes.

    Then you use an XmlSerializer class to read the xml and populate the classes.

    I've created a couple of these classes that load up the Store.xml.

    First let's look at how those classes are called:
    class Program
    Code:
        {
    static void Main( string [ ] args )
    {
                var store = Store.FromXml("store.xml");
    
                Console.WriteLine( "First Catalog:" );
    
                foreach( var book in store.CatalogFirst.Books )
                {
                    DisplayBook( book );
                }
    
                Console.WriteLine( "Second Catalog:" );
    
                foreach ( var book in store.CatalogSecond.Books )
                {
                    DisplayBook( book );
                }
            }
    
            static void DisplayBook( Book book )
            {
                Console.WriteLine( String.Format( "\t{0,-16}{1}", "Id:", book.Id ) );
                Console.WriteLine( String.Format( "\t{0,-16}{1}", "Author:", book.Author ) );
                Console.WriteLine( String.Format( "\t{0,-16}{1}", "Title:", book.Title ) );
                Console.WriteLine( String.Format( "\t{0,-16}{1}", "Genre:", book.Genre ) );
                Console.WriteLine( String.Format( "\t{0,-16}${1}", "Price:", book.Price ) );
                Console.WriteLine( String.Format( "\t{0,-16}{1}", "Date Published:", book.DatePublished.ToShortDateString( ) ) );
                Console.WriteLine( String.Format( "\t{0,-16}{1}\n", "Description:", book.Description ) );
            }
    }
    This results in the following output:
    Code:
    First Catalog:
            Id:             bk101
            Author:         Gambardella, Matthew
            Title:          XML Developer's Guide
            Genre:          Computer
            Price:          $44.95
            Date Published: 10/1/2000
            Description:
            An in-depth look at creating applications
            with XML.
    
    
            Id:             bk102
            Author:         Ralls, Kim
            Title:          Midnight Rain
            Genre:          Fantasy
            Price:          $5.95
            Date Published: 12/16/2000
            Description:
            A former architect battles corporate zombies,
            an evil sorceress, and her own childhood to become queen
            of the world.
    
    
    Second Catalog:
            Id:             bk103
            Author:         Corets, Eva
            Title:          Maeve Ascendant
            Genre:          Fantasy
            Price:          $5.95
            Date Published: 11/17/2000
            Description:
            After the collapse of a nanotechnology
            society in England, the young survivors lay the
            foundation for a new society.
    
    
            Id:             bk104
            Author:         Corets, Eva
            Title:          Oberon's Legacy
            Genre:          Fantasy
            Price:          $5.95
            Date Published: 3/10/2001
            Description:
            In post-apocalypse England, the mysterious
            agent known only as Oberon helps to create a new life
            for the inhabitants of London. Sequel to Maeve
            Ascendant.
    Notice that loading and accessing the book collection is pretty simple:
    Code:
    var store = Store.FromXml("store.xml");
    
    foreach( var book in store.CatalogFirst.Books )
    {
      DisplayBook( book );
    }
    Next, let's look at the classes used to represent the xml:
    Code:
    using System;
    using System.Collections.Generic;
    using System.Xml;
    using System.Xml.Serialization;
    
    namespace CG.XmlSerialization
    {
        [XmlRoot( ElementName = "store", Namespace = "" )]
        public class Store
        {
            public static Store FromXml( string xmlFile )
            {
                var serializer = new XmlSerializer(typeof (Store) );
    
                using( var reader = XmlReader.Create( xmlFile ) )
                {
                    return (Store) serializer.Deserialize( reader );
                }
            }
    
            public Store()
            {
                CatalogFirst = new Catalog( );
                CatalogSecond = new Catalog( );
            }
    
            [XmlElement( "firstCatalog" )]
            public Catalog CatalogFirst { get; set; }
    
            [XmlElement( "secondCatalog" )]
            public Catalog CatalogSecond { get; set; }
        }
    
        public class Catalog
        {
            [XmlElement( "book")]
            public Book[] Books
            {
                get
                {
                    if( _bookList == null ) _bookList = new List<Book>( );
    
                    return _bookList.ToArray( );
                }
    
                set
                {
                    if ( _bookList == null ) _bookList = new List<Book>( );
    
                    if( value != null )
                    {
                        _bookList.AddRange( value );
                    }
                }
            }
    
            private List<Book> _bookList = new List<Book>( );
        }
    
        public class Book
        {
            [XmlAttribute( "id")]
            public string Id { get; set; }
    
            [XmlElement( "author" )]
            public string Author { get; set; }
    
            [XmlElement( "title" )]
            public string Title { get; set; }
    
            [XmlElement( "genre" )]
            public string Genre { get; set; }
    
            [XmlElement( "price" )]
            public decimal Price { get; set; }
    
            [XmlElement( "publish_date" )]
            public DateTime DatePublished { get; set; }
    
            [XmlElement( "description" )]
            public string Description { get; set; }
        }
    }
    You'll notice the Store class has an XmlRoot attribute which allows you to specify the root node ("store") and the namespace (blank in this case).

    The Store class contains a FromXml static method, that uses an Xml Serializer object to create and populate an instance of the Store class.

    The Store class also contains two properties CatalogFirst and Catalog second. These each contain a collection of books.

    The Catalog class is simply and contains only one Books property which is an array of Book objects. You'll notice that a List<Book> object is used to back this property. That way, clients calling the Catalog classes will be assurred that the Books array is never null. For a similar reason, the CatalogFirst and CatalogSecond properties are always initialized (even if their corresponding Books properties are empty).

    The Book class has an Id property with an XmlAttribute markup attribute. This indicates that the id property is an xml attribute. The remaining properties all have XmlElement markup attributes (to indicate that these are xml element nodes).

    You'll notice that the properties such as Price and DatePublished can be actual data types (Decimal, and DateTime) rather than just strings. All this is done to prevent the user of the class to have to convert the types before using them.

    Really the end goal is to use the Store class, like a C# class and be able to enumerate its Books collections with a foreach loop (like you would do for most enumerations). This implementation kind of hides the fact that the Store class was initially populated by xml (which is how it should be).

    As you can s

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured