从XML读取数据 [英] Reading data from XML

查看:118
本文介绍了从XML读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算使用XML数据库的目的。只有我能够做的事情是阅读整个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.

下面是一个简单的XML

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

我只是想学习如何读取XML不是整个文件的具体数据。

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

[解决]
我已经使用LINQ到XML

[SOLVED] I have used Linq to XML

推荐答案

我不认为你可以合法地只加载一个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).

使用LINQ到XML,你可以做 VAR DOC = XDocument.Load(yourfilepath)。从那里,它只是查询你想要的数据的问题,这样说:

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") );

心连心。

编辑:

好吧,只是为了做出更好的样本,试试这个(以@ JWL_的建议改进):

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();
        }
    }
}

您将需要调整路径XDocument.Load()来指向您的XML文件,但其余的应该工作。询问哪些部分你不明白的问题。

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.

这篇关于从XML读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆