我正在尝试将来自AdWords API的XML反序列化为模型列表。这是XML格式:
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<report>
<report-name name='GeoPerformance Report for 5/26/2014 12:00:00 AM'/>
<date-range date='May 26, 2014'/>
<table>
<columns>
<column name='clicks' display='Clicks'/>
<column name='countryTerritory' display='Country/Territory'/>
<column name='day' display='Day'/>
</columns>
<row clicks='24286' countryTerritory='United States' day='2014-05-26'/>
<row clicks='26' countryTerritory='Africa' day='2014-05-26'/>
<row clicks='286' countryTerritory='Europe' day='2014-05-26'/>
<row clicks='242' countryTerritory='Asia' day='2014-05-26'/>
</table>
</report>
我的模特课是:
[XmlRoot("report")]
public class AdWordsGeoPerformance
{
public int Clicks { get; set; }
public string CountryTerritory { get; set; }
public DateTime Day { get; set; }
}
我希望每行的属性(click,countryTerritory,day)映射到AdWordsGeoPerformance的实例。
关于我如何做到这一点的任何建议?
答案 0 :(得分:0)
您可以尝试使用xsd工具生成类:
xsd your.xsd /classes
在快速搜索中,我发现了这个: https://adwords.google.com/api/adwords/reportdownload/v201109/reportDefinition.xsd
我不确定这是否是正确的架构,如果没有找到它(应该在文档中说明)并使用它来生成你的类。
答案 1 :(得分:-1)
我倾向于支持Linq对XML进行反序列化。您必须使用许多对象玩一些游戏才能序列化/反序列化该数据。对我来说,使用XDocument要容易得多。
如果您正在寻找替代方法,这可能会有所帮助:
var adWords = new List<AdWordsGeoPerformance>();
var xDoc = XDocument.Parse(doc);
foreach(var r in xDoc.Descendants("row"))
{
var adWord = new AdWordsGeoPerformance()
{
Clicks = int.Parse((string)r.Attribute("clicks")),
CountryTerritory = (string)r.Attribute("countryTerritory"),
Day = DateTime.Parse((string)r.Attribute("day")),
};
adWords.Add(adWord);
}