Reputation: 3711
I have xml document (you may look it up here) from web request.
I need to get values of ccy, base_ccy, buy and sale attributes from each "exchangerate" element:
<exchangerate ccy="EUR" base_ccy="UAH" buy="10.81284" sale="10.81284"/>
I've manually created class ExchangeRate, which is looks like this:
[Serializable]
public class ExchangeRate
{
[XmlAttribute("ccy")]
public string Ccy
{ get; set; }
[XmlAttribute("base_ccy")]
public string Base_ccy
{ get; set; }
[XmlAttribute("buy")]
public string Buy
{ get; set; }
[XmlAttribute("sale")]
public string Sale
{ get; set; }
}
and trying to deserialize xml-element "exchangerate" (which I've isolate from whole xml-document) to the instance of ExchangeRate class in this way:
private ExchangeRate DesereilizeXMLNode(XmlNode node)
{
XmlSerializer mySerializer = new XmlSerializer(typeof(ExchangeRate));
TextReader reader = new StringReader(node.OuterXml);
return (ExchangeRate)mySerializer.Deserialize(reader);
}
When I debuging DesereilizeXMLNode method I receiving exception while calling deserialization method. The exception is XAMLParseException in MainWindow.xaml in first line of the Grid element (which is weird) and I think it is not a proper place for calling exception.
The question is: where was I wrong? Am I wrong when tried to create an object instance from xml-element in this way? Maybe I've made mistake when tried to deserialize only xml-element with attributes without deserialization of whole xml-document?
Upvotes: 1
Views: 3211
Reputation: 2977
You have to specify a Serializable for the whole syntax of the XML file for the Deserialize to work! So from the root node in the XML down to this node. (I can't give you an example as your lookup url is not working for me; 501)
EDIT:
Well then you will have to find the elements and their attributes manually, like the example below. You can't individually Deserialize XmlElements, unless you convert them to an XmlDocument, but that's a bit overdone.
XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
XmlNodeList nodes = doc.SelectNodes("/account_order/row/exchangerate");
foreach (XmlNode node in nodes)
{
XmlAttribute ccyAttribute = node.Attributes["ccy"];
//etc...
}
Upvotes: 2
Reputation: 107
You would have to deserialize the whole document - I think it mightbe easier for you, to find the exchangerate elements you need with xpath. Then write a 'manual deserialiser' that reads the value of each element and populate the properties of an ExchangeRate object.
Upvotes: 1