gpt4 book ai didi

c# - 使用指定为 "utf-16"的编码解析 xml 时出现 XmlException

转载 作者:行者123 更新时间:2023-11-30 12:10:10 25 4
gpt4 key购买 nike

我在解析具有 utf-16 编码但工作正常的 XML 时遇到问题使用 utf-8 没问题。
任何人都可以帮助我解决这个问题吗?

我收到以下错误:

System.Web.HttpUnhandledException' was thrown.<br/>
System.Xml.XmlException: There is no Unicode byte order mark.<br/>
Cannot switch to Unicode

XML header :

<?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;
}

最佳答案

您可以根据 xml 内容的编码创建一个编码器:

string encoding = "UTF-8"; // should match encoding in XML
string xml = @"<?xml version='1.0' encoding='UTF-8'?><table><row>1</row></table>";

var ms = new MemoryStream(Encoding.GetEncoding(encoding).GetBytes(xml));

var xdrs = new XmlReaderSettings()
{IgnoreComments = true,
IgnoreWhitespace = true,
CloseInput = true};

var xdr = XmlReader.Create(ms, xdrs);
while (xdr.Read())
{
Console.Write("qqq");
}

关于编码的更多信息,有一个相关的question

关于c# - 使用指定为 "utf-16"的编码解析 xml 时出现 XmlException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19278470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com