gpt4 book ai didi

c# - 将xml反序列化为c#对象

转载 作者:太空宇宙 更新时间:2023-11-03 22:04:16 25 4
gpt4 key购买 nike

我有以下 xml(我无法编辑):

<?xml version="1.0" encoding="UTF-8"?>

<ns0:prices xmlns:ns0="http://schemas.some.com/sadas/Output">
<pricepoint>
<esid>
ENG.GPL.DAY_AHEAD.PROMPT.PH.M
</esid>
<observationdate>20120123</observationdate>
<observationtime>0000</observationtime>
<price>22.1250</price>
<quote>Q</quote>
</pricepoint>
<pricepoint>
<esid>
ENG.NBP.DAY_AHEAD.PROMPT.PH.M
</esid>
<observationdate>20120123</observationdate>
<observationtime>0000</observationtime>
<price>53.8500</price>
<quote>Q</quote>
</pricepoint>
<pricepoint>
<esid>
ENG.NCG.DAY_AHEAD.PROMPT.PH.M
</esid>
<observationdate>20120123</observationdate>
<observationtime>0000</observationtime>
<price>22.0750</price>
<quote>Q</quote>
</pricepoint>
<pricepoint>
<esid>
ENG.TTF.DAY_AHEAD.PROMPT.PH.M
</esid>
<observationdate>20120123</observationdate>
<observationtime>0000</observationtime>
<price>21.9500</price>
<quote>Q</quote>
</pricepoint>
<pricepoint>
<esid>
ENG.ZEEBRUGGE.DAY_AHEAD.PROMPT.PH.M
</esid>
<observationdate>20120123</observationdate>
<observationtime>0000</observationtime>
<price>53.6500</price>
<quote>Q</quote>
</pricepoint>
</ns0:prices>

我想将其映射到以下对象:

[Serializable]
public class Prices
{

public List<Pricepoint> prices { get; set; }
}

[Serializable]
public class Pricepoint
{

public string Esid { get; set; }

public DateTime Observationdate { get; set; }

public int Observationtime { get; set; }

public double Price { get; set; }

public string Quote { get; set; }

}

使用以下方法:

    public static object Deserialize(Type typeToDeserialize,byte[] bytes)
{
var mem = new MemoryStream(bytes);
var ser = new XmlSerializer(typeToDeserialize);
return ser.Deserialize(mem);
}

Deserialize(typeof(Prices), byteArrayofXMLfile); 调用

但是我确实收到了关于 xml 的命名空间行的错误:

There is an error in XML document (3, 2)

我不知道我做错了什么?

最佳答案

编辑:刚刚重新阅读,发现您在询问命名空间。使用 XmlRootAttributeNamespace 属性,如下所示。


您需要通过属性告诉 XmlSerializer 哪些标签映射到哪些属性:

[Serializable]
[XmlRoot(Namespace = "http://www.ZomboCorp.com/", ElementName="prices")]
public class Prices
{
[XmlElement("pricepoint")]
public List<Pricepoint> prices { get; set; }
}

[Serializable]
public class Pricepoint
{

[XmlElement("esid")]
public string Esid { get; set; }

[XmlElement("observationdate")]
public DateTime Observationdate { get; set; }

[XmlElement("observationtime")]
public int Observationtime { get; set; }

[XmlElement("price")]
public double Price { get; set; }

[XmlElement("quote")]
public string Quote { get; set; }

}

关于c# - 将xml反序列化为c#对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8994293/

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