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

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

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

但只需要 encoding="utf-8"

只有没有引号的“utf-8”,我如何使用streamreader来实现这一点?


守着星空守着你
浏览 237回答 3
3回答

眼眸繁星

您需要utf-8或encoding="utf-8"吗?该块因此返回utf-8。如果需要 encoding="utf-8",则需要更改。using (var sr = new StreamReader(@"yourXmlFilePath")){&nbsp; &nbsp; var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };&nbsp; &nbsp; using (var xmlReader = XmlReader.Create(sr, settings))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!xmlReader.Read()) throw new Exception("No line");&nbsp; &nbsp; &nbsp; &nbsp; var result = xmlReader.GetAttribute("encoding"); //returns utf-8&nbsp; &nbsp; }}

叮当猫咪

因为它是 xml,所以我会推荐XmlTextReader,它提供对 XML 数据的快速、非缓存、仅向前访问,并且因为声明在那里而只读取 xml 文件的顶部。请参阅以下方法:string FindXmlEncoding(string path){&nbsp; &nbsp; XmlTextReader reader = new XmlTextReader(path);&nbsp; &nbsp; reader.Read();&nbsp; &nbsp; if (reader.NodeType == XmlNodeType.XmlDeclaration)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; while (reader.MoveToNextAttribute())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (reader.Name == "encoding")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return reader.Value;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return null;}

肥皂起泡泡

我怎样才能做到这一点StreamReader?像这样的东西:using (StreamReader sr = new StreamReader("XmlFile.xml")){&nbsp; &nbsp; string line = sr.ReadLine();&nbsp; &nbsp; int closeQuoteIndex = line.LastIndexOf("\"") - 1;&nbsp; &nbsp; int openingQuoteIndex = line.LastIndexOf("\"", closeQuoteIndex);&nbsp; &nbsp; string encoding = line.Substring(openingQuoteIndex + 1, closeQuoteIndex - openingQuoteIndex);}
打开App,查看更多内容
随时随地看视频慕课网APP