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
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With