如何使用StreamReader提取xml文件编码?

时间:2018-08-09 12:40:12

标签: c# xml stream

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

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

但仅需要编码=“ utf-8”

仅带引号的“ utf-8”,如何使用streamreader实现?

4 个答案:

答案 0 :(得分:1)

  

如何使用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);
}

答案 1 :(得分:1)

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

答案 2 :(得分:1)

由于它是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 :(得分:1)

您需要 utf-8 encoding =“ 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

    }
}