【问题标题】:How can I extract xml file encoding using streamreader?如何使用 streamreader 提取 xml 文件编码?
【发布时间】:2018-08-09 12:40:12
【问题描述】:

我需要从 xml 文件的顶部获取编码类型

<?xml version=“1.0” encoding=“utf-8”?>

但只需要 encoding="utf-8"

“utf-8”只有不带引号,如何使用streamreader实现?

【问题讨论】:

  • 可以忽略xml的第一行。所以我通常只使用 reader.ReadLine() 它将跳过第一行。给出错误的不是流阅读器。是 XmlReader 出错了。
  • 如果将其加载到 XDocument 中,您可以询问 .Declaration.Encoding

标签: c# xml stream


【解决方案1】:

您需要 utf-8encoding="utf-8" 吗?此块返回 utf-8 作为结果。如果需要encoding="utf-8",则需要更改。

using (var sr = new StreamReader(@"yourXmlFilePath"))
{
    var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };

    using (var xmlReader = XmlReader.Create(sr, settings))
    {
        if (!xmlReader.Read()) throw new Exception("No line");

        var result = xmlReader.GetAttribute("encoding"); //returns utf-8

    }
}

【讨论】:

    【解决方案2】:

    因为它是 xml,所以我推荐 XmlTextReader,它提供对 XML 数据的快速、非缓存、只进的访问,并且只读取 xml 文件的顶部,因为声明在那里。见以下方法:

    string FindXmlEncoding(string path)
    {
        XmlTextReader reader = new XmlTextReader(path);
        reader.Read();
        if (reader.NodeType == XmlNodeType.XmlDeclaration)
        {
            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "encoding")
                    return reader.Value;
            }
        }
        return null;
    }
    

    【讨论】:

      【解决方案3】:

      如何使用StreamReader 实现这一点?

      类似这样的:

      using (StreamReader sr = new StreamReader("XmlFile.xml"))
      {
          string line = sr.ReadLine();
          int closeQuoteIndex = line.LastIndexOf("\"") - 1;
          int openingQuoteIndex = line.LastIndexOf("\"", closeQuoteIndex);
          string encoding = line.Substring(openingQuoteIndex + 1, closeQuoteIndex - openingQuoteIndex);
      }
      

      【讨论】:

        【解决方案4】:
        const string ENCODING_TAG = "encoding"; //You are searching for this. Lets make it constant.
        
        
        string line = streamReader.ReadLine();    //Use your reader here
        int start = line.IndexOf(ENCODING_TAG);
        start = line.IndexOf('"', start)+1;       //Start of the value
        int end = line.IndexOf('"', start);       //End of the value
        string encoding = line.Substring(start, end-start);
        

        注意:这种方法要求编码位于现有声明的第一行。 Which it does not need to be.

        【讨论】:

          猜你喜欢
          • 2023-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多