0

I have the following sample XML:

<PossibleAddresses>
    <Address tempid="12345">1 The Street England</Address>
    <Address tempid="6789">2 The Street England</Address>
    <Address tempid="4321">3 The Street England</Address>
    <Address tempid="1111">4 The Street England</Address>
</PossibleAddresses>

I am trying to deserialize this XML so that I essentially just get back a list of 'Address' objects that contains two properties. One being the 'tempid' the other being the actual address string itself.

My class looked something like this:

[XmlRoot("PossibleAddresses")]
    public class Addresses
    {
        [XmlArrayItem("Address", Type = typeof(Address))]
        public List<Address> PossibleAddresses { get; set; }
    }

    public class Address
    {
        [XmlAttribute(AttributeName = "tempid")]
        public string TempId { get; set; }

        [XmlElement(ElementName = "Address")]
        public string FullAddress { get; set; }
    }

I am then using the XmlSerializer to deserialize the XML. With T being the class 'Addresses':

public static T DeserializeObject<T>(string data)
        {
            var ser = new XmlSerializer(typeof(T));
            return (T)ser.Deserialize(new StringReader(data));
        }

Currently this will deserialize successfully. I just end up with an empty list of addresses.

1
  • 1
    You'll also need to change the decoration of PossibleAddresses to [XmlElement("Address", Type = typeof(Address))]public List<Address> PossibleAddresses { get; set; } Commented Mar 20, 2015 at 14:22

2 Answers 2

3

FullAddress here should be with attribute XmlText

[XmlText]
public string FullAddress { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

1

GoogleHireMe is correct that you need an XmlText attribute.

public class Address
{
    [XmlAttribute(AttributeName = "tempid")]
    public string TempId { get; set; }
    [XmlText]
    public string FullAddress { get; set; }
}

However, you can deserialize the addresses directly as an array:

var serializer =
    new XmlSerializer(
        typeof(Address[]),
        new XmlRootAttribute("PossibleAddresses"));
Address[] items;

using(var stream = new StringReader(xml))
using(var reader = XmlReader.Create(stream))
{
    items = (Address[]) serializer.Deserialize(reader);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.