gpt4 book ai didi

c# XMLSerializer 返回 null

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

private ResultReferences<T> GetList<T>(string result) where T : class
{
TextReader reader = new StringReader(result);
XmlSerializer serializer = new XmlSerializer(typeof(ResultReferences<T>));
ResultReferences<T> response = (ResultReferences<T>)serializer.Deserialize(reader);
return response;
}

这是解析字符串xml的函数:

这是我的 xml 字符串:

<?xml version="1.0" encoding="UTF-8"?>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/some-api/ getCurrencyRate.xsd">
<rates date="2015-07-07">
<item cur1="USD" cur2="RUR">57.8215</item>
<item cur1="EUR" cur2="RUR">63.9852</item>
<item cur1="EUR" cur2="USD">1.1177</item>
<item cur1="USD" cur2="EUR">0.9037</item>
</rates>
</result>

正好在一行中:

        ResultReferences<T> response = (ResultReferences<T>)serializer.Deserialize(reader);

返回null,这是为什么呢?我的 xml 错了吗?

这是序列化代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace mynamespace
{
[XmlType(TypeName = "currency")]
public class oCurrency
{
[XmlAttribute]
public long id { get; set; }
[XmlAttribute]
public string name { get; set; }
}
}

最佳答案

这是对应于您发布的 XML 的 C# 代码:

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="item")]
public class Item {
[XmlAttribute(AttributeName="cur1")]
public string Cur1 { get; set; }
[XmlAttribute(AttributeName="cur2")]
public string Cur2 { get; set; }
[XmlText]
public string Text { get; set; }
}

[XmlRoot(ElementName="rates")]
public class Rates {
[XmlElement(ElementName="item")]
public List<Item> Item { get; set; }
[XmlAttribute(AttributeName="date")]
public string Date { get; set; }
}

[XmlRoot(ElementName="result")]
public class Result {
[XmlElement(ElementName="rates")]
public Rates Rates { get; set; }
[XmlAttribute(AttributeName="xsi", Namespace="http://www.w3.org/2000/xmlns/")]
public string Xsi { get; set; }
[XmlAttribute(AttributeName="schemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")]
public string SchemaLocation { get; set; }
}
}

generated , 当然;这就是为什么它如此精确。无论如何,它与您提供的 C# 类几乎没有相似之处。

关于c# XMLSerializer 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31259711/

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