简体   繁体   English

从控制台应用程序读取网站上的XML文件

[英]Reading XML file from website from console application

What I want to accomplish is reading an xml file from a website ( http://xml.buienradar.nl/ ). 我想要完成的是从网站( http://xml.buienradar.nl/ )读取xml文件。 I have been reading about what to use, but I can't see the forest for the trees! 我一直在阅读有关使用什么的内容,但我无法看到森林中的树木! Should I be using WebRequest, or XmlDocument, or XDocument, or XmlReader, or XmlTextReader, or? 我应该使用WebRequest,XmlDocument,XDocument,XmlReader,XmlTextReader,还是? I read that XmlDocument and XDocument read the whole file into memory, and XmlReader doesn't. 我读到XmlDocument和XDocument将整个文件读入内存,而XmlReader则没有。 But is that a problem in this case? 但在这种情况下这是一个问题吗? What if indeed the xml file is huge? 如果xml文件确实很大怎么办?

Can someone help me find a way? 有人能帮我找路吗?

Thanks! 谢谢!

To read huge XML without loading all of it into memory, you can use XmlReader class. 要读取大量XML而不将所有XML加载到内存中,可以使用XmlReader类。 But please note that this method requires more code than XDocument or even XmlDocument solution. 但请注意,此方法需要的代码多于XDocument甚至XmlDocument解决方案。

var h = WebRequest.CreateHttp("http://xml.buienradar.nl/");

using (var r = h.GetResponse())
using (var resp = r.GetResponseStream())    
using (var sr = new StreamReader(resp))    
using (var xr = new XmlTextReader(sr))       
{ 
    while (xr.Read())
    {
        // doing something with xr
        // for example print it's current node value
        Console.WriteLine(xr.Value);
    }
}   

If you want to test for large XML file, you can try XML from http://www.ins.cwi.nl/projects/xmark/Assets/standard.gz . 如果要测试大型XML文件,可以从http://www.ins.cwi.nl/projects/xmark/Assets/standard.gz尝试XML。

It is over 30 MB gzipped. 它是超过30 MB的压缩。 With this method, XML processing don't require much memory, it even don't wait for whole file to finished downloading. 使用这种方法,XML处理不需要太多内存,甚至不等待整个文件完成下载。

Test code: 测试代码:

var h = WebRequest.CreateHttp("http://www.ins.cwi.nl/projects/xmark/Assets/standard.gz");

using (var r = h.GetResponse())
using (var resp = r.GetResponseStream())
using (var decompressed = new GZipStream(resp, CompressionMode.Decompress))
using (var sr = new StreamReader(decompressed))
using (var xr = new XmlTextReader(sr))
{
    while (xr.Read())
    {
        // doing something with xr
        // for example print it's current node value
        Console.WriteLine(xr.Value);
    }
}

XmlTextReader provides a faster mechanism for reading xml. XmlTextReader提供了一种更快的读取xml的机制。

string url="http://xml.buienradar.nl/";

XmlTextReader xml=new XmlTextReader(url);

while(xml.Read())
{
   Console.WriteLine(xml.Value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM