gpt4 book ai didi

c# - 将此 XML 反序列化为对象的最佳方法

转载 作者:太空狗 更新时间:2023-10-29 22:08:36 25 4
gpt4 key购买 nike

在我见过的其他示例中,与我的类似,有一个根节点,然后是一个数组节点,然后是一堆数组项。我的问题是,我的根节点我的数组节点,所以我看到的示例似乎对我不起作用,而且我无法更改 XML 架构。这是 XML:

<articles>  
<article>
<guid>7f6da9df-1a91-4e20-8b66-07ac7548dc47</guid>
<order>1</order>
<type>deal_abstract</type>
<textType></textType>
<id></id>
<title>Abu Dhabi's IPIC Eyes Bond Sale After Cepsa Buy</title>
<summary>Abu Dhabi's IPIC has appointed banks for a potential sterling and euro-denominated bond issue, a document showed on Wednesday, after the firm acquired Spain's Cepsa in a $5 billion deal earlier this month...</summary>
<readmore></readmore>
<fileName></fileName>
<articleDate>02/24/2011 00:00:00 AM</articleDate>
<articleDateType></articleDateType>
</article>

<article>
<guid>1c3e57a0-c471-425a-87dd-051e69ecb7c5</guid>
<order>2</order>
<type>deal_abstract</type>
<textType></textType>
<id></id>
<title>Big Law Abuzz Over New China Security Review</title>
<summary>China’s newly established foreign investment M&amp;A review committee has been the subject of much legal chatter in the Middle Kingdom and beyond. Earlier this month, the State Council unveiled legislative guidance on…</summary>
<readmore></readmore>
<fileName></fileName>
<articleDate>02/23/2011 00:00:00 AM</articleDate>
<articleDateType></articleDateType>
</article>
</articles>

这是我的类(class):

public class CurrentsResultsList
{
public Article[] Articles;
}

public class Article
{
public string Guid { get; set; }
public int Order { get; set; }
public string Type { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public DateTime ArticleDate { get; set; }
}

这是来自外部 API 的 XML 响应。

最佳答案

  1. 将它放在 visual studio 中的 xml 中

  2. 创建 xsd 模式

  3. 使用:

    "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\xsd.exe" "MyXsd.xsd" /t:lib /l:cs /c  /namespace:my.xsd /outputdir:"C:\testtttt"  

现在您的 C# 类已准备就绪。
你可以使用这个:

internal class ParseXML 
{
public static xsdClass ToClass<xsdClass>(XElement ResponseXML)
{
return deserialize<xsdClass>(ResponseXML.ToString(SaveOptions.DisableFormatting));
}

private static result deserialize<result>(string XML)
{
using (TextReader textReader = new StringReader(XML))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(result));
return (result) xmlSerializer.Deserialize(textReader);
}
}
}

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

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