我打算将XML用于数据库目的.我唯一能做的就是读取整个XML文件.我希望能够只读取一些数据,但我不知道该怎么做.
这是一个简单的XML
<Books>
<Book>
<Title>Animals</Title>
<Author>J. Anderson</Author>
</Book>
<Book>
<Title>Car</Title>
<Author>L. Sawer</Author>
</Book>
</Books>
Run Code Online (Sandbox Code Playgroud)
我对应用程序的输出感兴趣
Books:
Animals
Cars
Authors:
J. Anderson
L. Sawer
Run Code Online (Sandbox Code Playgroud)
我只想学习如何从XML读取特定数据而不是整个文件.
[已解决]我已将Linq用于XML
Tie*_* T. 48
我认为你不能"合法地"加载XML文件的一部分,因为那时它会格式不正确(某处会有一个缺少的关闭元素).
使用LINQ-to-XML,你可以做到var doc = XDocument.Load("yourfilepath")
.从那里只需要查询你想要的数据,比如说:
var authors = doc.Root.Elements().Select( x => x.Element("Author") );
Run Code Online (Sandbox Code Playgroud)
HTH.
编辑:
好的,只是为了让它成为更好的样本,试试这个(使用@ JWL_建议的改进):
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您需要调整路径XDocument.Load()
以指向XML文件,但其余部分应该有效.询问有关您不理解哪些部分的问题.
Pao*_*lla 12
根据@Jon Skeet的评论,只有当你的文件很大时才应该使用XmlReader.这是如何使用它.假设你有一个Book类
public class Book {
public string Title {get; set;}
public string Author {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
你可以逐行读取XML文件,内存占用空间很小,如下所示:
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};
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
198035 次 |
最近记录: |