Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from XML [duplicate]

Tags:

c#

database

xml

I'm planning to use XML for database purpose. Only thing I was able to do is read whole XML file. I want to be able to read only some data and I don't know how to do that.

Here is a simple XML

<Books>
 <Book>
  <Title>Animals</Title>
  <Author>J. Anderson</Author>
 </Book>
 <Book>
  <Title>Car</Title>
  <Author>L. Sawer</Author>
 </Book>
</Books> 

I'm interested in app where output is gonna be

Books:
Animals
Cars

Authors:
J. Anderson
L. Sawer

I'm just want to learn how read specific data from XML not whole file.

[SOLVED] I have used Linq to XML

like image 784
Safiron Avatar asked Aug 19 '11 09:08

Safiron


2 Answers

I don't think you can "legally" load only part of an XML file, since then it would be malformed (there would be a missing closing element somewhere).

Using LINQ-to-XML, you can do var doc = XDocument.Load("yourfilepath"). From there its just a matter of querying the data you want, say like this:

var authors = doc.Root.Elements().Select( x => x.Element("Author") );

HTH.

EDIT:

Okay, just to make this a better sample, try this (with @JWL_'s suggested improvement):

using System;
using System.Xml.Linq;

namespace ConsoleApplication1 {
    class Program {
        static void Main( string[] args )  {
            XDocument doc = XDocument.Load( "XMLFile1.xml" );
            var authors = doc.Descendants( "Author" );
            foreach ( var author in authors ) {
                Console.WriteLine( author.Value );
            }
            Console.ReadLine();
        }
    }
}

You will need to adjust the path in XDocument.Load() to point to your XML file, but the rest should work. Ask questions about which parts you don't understand.

like image 153
Tieson T. Avatar answered Oct 30 '22 00:10

Tieson T.


as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class

public class Book {
    public string Title {get; set;}
    public string Author {get; set;}
}

you can read the XML file line by line with a small memory footprint, like this:

public static class XmlHelper {
    public static IEnumerable<Book> StreamBooks(string uri) {
        using (XmlReader reader = XmlReader.Create(uri)) {
            string title = null;
            string author = null;

            reader.MoveToContent();
            while (reader.Read()) {
                if (reader.NodeType == XmlNodeType.Element
                    && reader.Name == "Book") {
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "Title") {
                            title = reader.ReadString();
                            break;
                        }
                    }
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "Author") {
                            author =reader.ReadString();
                            break;
                        }
                    }
                    yield return new Book() {Title = title, Author = author};
                }
            }       
        }
    }

Example of usage:

string uri = @"c:\test.xml"; // your big XML file

foreach (var book in XmlHelper.StreamBooks(uri)) {
    Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);  
}
like image 12
Paolo Falabella Avatar answered Oct 29 '22 23:10

Paolo Falabella