Reputation: 1568
I have the following XML, but I'm not able to deserialize to the object I need.
<response>
<texts>
<text name="blabla">This is bla</text>
<text name="test xpto">This is a text</text>
(…)
</texts>
</response>
This is what I've tried so far:
public class ResponseTexts : Response
{
[XmlArray(ElementName = "texts")]
[XmlArrayItem(ElementName = "text"]
public List<Text> Texts { get; set; }
}
public class Text
{
[XmlElement(ElementName = "text")]
public string TextValue { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}
But so far the TextValue always come as null....can someone enlight me?
thanks in advance
Upvotes: 2
Views: 598
Reputation: 236208
You should use XmlText to get element value. Here is correct serialziation attributes:
[XmlRoot("response")]
public class Response
{
[XmlArray(ElementName = "texts")]
[XmlArrayItem(ElementName = "text")]
public List<Text> Texts { get; set; }
}
public class Text
{
[XmlText]
public string TextValue { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}
Deserialization:
var serializer = new XmlSerializer(typeof(Response));
using(var stream = File.OpenRead(path_to_xml))
{
var response = (Response)serializer.Deserialize(stream);
}
Result:
{
Texts: [
{ TextValue: "This is bla", Name: "blabla" },
{ TextValue: "This is a text", Name: "test xpto" }
]
}
Upvotes: 4
Reputation: 1121
In visual studio 2013
:
Copy your XML in buffer (just select it and press CTRL+C
) go to Edit
-> Paste Special
-> Paste XML as Classes
Upvotes: 4