【问题标题】:Download and Unzip XML file下载并解压 XML 文件
【发布时间】:2017-05-12 05:39:09
【问题描述】:

我想解压并解析一个位于here的xml文件

这是我的代码:

HttpClientHandler handler = new HttpClientHandler()
{
    CookieContainer = new CookieContainer(),
    UseCookies = true,
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
   // | DecompressionMethods.None,

};

using (var http = new HttpClient(handler))
{

    var response =
         http.GetAsync(@"https://login.tradedoubler.com/report/published/aAffiliateEventBreakdownReportWithPLC_806880712_4446152766894956100.xml.zip").Result;

    Stream streamContent = response.Content.ReadAsStreamAsync().Result;

    using (var gZipStream = new GZipStream(streamContent, CompressionMode.Decompress))
    {
        var settings = new XmlReaderSettings()
        {
             DtdProcessing = DtdProcessing.Ignore
         };

         var reader = XmlReader.Create(gZipStream, settings);
         reader.MoveToContent();

         XElement root = XElement.ReadFrom(reader) as XElement;
     }
}

我在 XmlReader.Create(gZipStream, settings) 上遇到异常

GZip 标头中的幻数不正确。确保您传递的是 GZip 流

为了仔细检查我是否从网络上获取了格式正确的数据,我抓取了流并将其保存到一个文件中:

byte[] byteContent = response.Content.ReadAsByteArrayAsync().Result;
File.WriteAllBytes(@"C:\\temp\1111.zip", byteContent);

检查 1111.zip 后,它显示为一个格式良好的 zip 文件,其中包含我需要的 xml。

我被告知 here 我根本不需要 GZipStream,但如果我从代码中完全删除压缩流,并将 streamContent 直接传递给 xml 阅读器,我会得到一个异常:

“根级别的数据无效。第 1 行,位置 1。”

压缩或未压缩,我仍然无法解析这个文件。我做错了什么?

【问题讨论】:

    标签: c# .net xml-parsing compression xmlreader


    【解决方案1】:

    将流保存到本地文件夹后,使用 ZipFile 类对其进行解压缩。 像这样的:

        byte[] byteContent = response.Content.ReadAsByteArrayAsync().Result;
        string filename = @"C:\temp\1111.zip";
        File.WriteAllBytes(filename, byteContent);
    
        string destinationDir = @"c:\temp";
        string xmlFilename = "report.xml";
    
        System.IO.Compression.ZipFile.ExtractToDirectory(filename, destinationDir);
    
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(Path.Combine(destinationDir, xmlFilename));
    
        //xml reading goes here...
    

    【讨论】:

      【解决方案2】:

      相关文件以PKZip 格式编码,而不是GZip 格式。

      你需要一个不同的库来解压它,比如System.IO.Compression.ZipFile

      您通常可以通过文件扩展名来判断编码。 PKZip 文件常用.zip,而GZip 文件常用.gz

      见:Unzip files programmatically in .net

      【讨论】:

        猜你喜欢
        • 2021-03-07
        • 2016-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 2021-11-23
        • 1970-01-01
        • 2013-02-27
        相关资源
        最近更新 更多