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

查看:23
本文介绍了从 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 to 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-to-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") );

HTH.

好的,只是为了使它成为一个更好的样本,试试这个(@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天全站免登陆