gpt4 book ai didi

c# - 使用 UTF-8 编码反序列化 XML

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

我今天已经对此进行了很多搜索,但找不到如何使用 UTF-8 编码进行反序列化。

 <?xml version="1.0" encoding="UTF-8"?>
<AvailabilityRequestV2 xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance"
siteid="0000"
apikey="0000"
async="false" waittime="0">
<Type>4</Type>
<Id>159266</Id>
<Radius>0</Radius>
<Latitude>0</Latitude>
<Longitude>0</Longitude>
</AvailabilityRequestV2>

如果我试试这个

 string xmlString = File above;         
XmlSerializer serializer = new XmlSerializer(typeof(AvailabilityRequestV2));
AvailabilityRequestV2 request = (AvailabilityRequestV2)serializer.Deserialize(
new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));

如果我在 Debug模式下将鼠标悬停在请求上,我会得到:

     {<?xml version="1.0" encoding="utf-16"?><AvailabilityRequestV2 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
..................

我怎样才能强制成为 UTF-8?

我只看到序列化,但我没有看到反序列化。

最佳答案

您可以使用 StreamReader 并指定 UTF-8,您还可以告诉它使用 BOM(如果存在):

using (StreamReader reader = new StreamReader("my.xml",Encoding.UTF8,true)) {
XmlSerializer serializer = new XmlSerializer(typeof(SomeType));

object result = serializer.Deserialize(reader);
}

我不确定当 XML 阅读器遇到 XML 中的 encoding="utf-16" 指令时会发生什么,它可能会切换。

关于c# - 使用 UTF-8 编码反序列化 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15072758/

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