3 回答
TA贡献1873条经验 获得超9个赞
您需要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
}
}
TA贡献1776条经验 获得超12个赞
因为它是 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;
}
TA贡献1829条经验 获得超6个赞
我怎样才能做到这一点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);
}
- 3 回答
- 0 关注
- 236 浏览
添加回答
举报