Reading data from XML [duplicate]
I'm planning to use XML for database purpose. Only thing I was able to do is read whole 开发者_如何学JAVAXML 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);
}
Alternatively, you can use XPathNavigator:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();
string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");
..
/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
XPathNavigator navigator, string xpath) {
StringBuilder sb = new StringBuilder();
sb.Append(description);
XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
while (bookNodesIterator.MoveNext())
sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
return sb.ToString();
}
Try GetElementsByTagName method of XMLDocument class to read specific data or LoadXml method to read all data to xml document.
精彩评论