我在解析具有 utf-16 编码的 XML 时遇到问题,但它与 utf-8 完美配合。
任何人都可以帮助我解决这个问题吗?
我收到以下错误:
System.Web.HttpUnhandledException' was thrown.
System.Xml.XmlException: There is no Unicode byte order mark.
Cannot switch to Unicode
XML 标头:
<?xml version="1.0" encoding="utf-16"?>
<RiskAssessmentRequestValue xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
C# 代码隐藏:
rptTransformedXml.DataSource = parser.ExtractData(xml);
rptTransformedXml.DataBind();
public List<XmlDataExtract> ExtractData(string xml)
{
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(xml));
return ExtractData(stream);
}
public List<XmlDataExtract> ExtractData(Stream xmlStream)
{
XmlReaderSettings settings = new XmlReaderSettings
{
IgnoreComments = true,
IgnoreWhitespace = true,
CloseInput = true
};
XmlReader reader = XmlReader.Create(xmlStream, settings);
XmlPathBuilder pathBuilder = new XmlPathBuilder(reader);
List<XmlDataExtract> xmlDataList = new List<XmlDataExtract>();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.XmlDeclaration)
continue;
pathBuilder.Add();
CollectAttributeData(reader, xmlDataList, pathBuilder);
CollectElementData(reader, xmlDataList, pathBuilder);
}
return xmlDataList;
}