1

Ok, So I am serializing a class into xml to be sent as an HttpResponse. Part of the data is a list of 'states', and I just can't figure out how to format it they way I need it to be.

Right now the xml response looke like so:

<user id="x" date="x" ...>
    <state>
        <state name="Email" />
            <Value>email@mail.com</Value>
        </state>
    </state>
    <state>
        <state name="Level" />
            <Value>0</Value>
        </state>
    </state>
</user>

I don't want elements within one element, and to not be its own element, but the value of the state element. I wanted it to look like

<user id="x" date="x" ...>        
    <state name="Email">email@email.com</state>
    <state name="Level">0</state>
</user>

right now my classes are:

[XmlRoot("user")]
public class User {
    [XmlAttribute]
    public int Id { get; set; }

    [XmlAttribute]
    public DateTime Date { get; set; }

    [XmlArray]
    public List<State> State { get; set; }

}

public struct State {
    [XmlAttribute]
    public string Name { get; set; }

    public string Value { get; set; }
}

Could someone show me what I am doing wrong? I cannot change the expected output, the service that is receiving these responses is preexisting and out of my control.

Thanks.

MIke
  • 140
  • 10

1 Answers1

1

You need to mark the Value field of State as XmlText, and the List<State> field of User as XmlElement, and make a few minor element name changes, like so:

public struct State
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlText]
    public string Value { get; set; }

    public override string ToString()
    {
        return string.Format("Name={0}, Value=\"{1}\"", Name, Value);
    }
}

[XmlRoot("user")]
public class User
{
    [XmlAttribute("id")]
    public int Id { get; set; }

    [XmlAttribute("date")]
    public DateTime Date { get; set; }

    [XmlElement("state")]
    public List<State> State { get; set; }
}

By the way, XmlSerializer requires DateTime field values to be in a very precise format. If your XML dates are not in this format, you will need to manually parse the field.

Then, when I do:

        var newUser = new User() { Id = 1, Date = DateTime.Today, State = new State[] { new State() { Name = "Email", Value = "email@mail.com" }, new State() { Name = "Level", Value = "0" } }.ToList() };
        var newXml = newUser.GetXml();
        Debug.WriteLine(newXml);

I get the output:

<?xml version="1.0" encoding="utf-16"?>
<user xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="1" date="2014-12-08T00:00:00-05:00">
    <state name="Email">email@mail.com</state>
    <state name="Level">0</state>
</user>
Community
  • 1
  • 1
dbc
  • 104,963
  • 20
  • 228
  • 340