1

In a project I am working on I have been given XML to work with that I have no control over. I need to pull out an array of nodes as well as a singular property that is a sibling of the array. (See sample XML below)

<pagination>
    <total-pages>1</total-pages>
    <page position="first">?i=1;q=gloves</page>
    <page position="last">?i=1;q=gloves</page>
    <page position="1" selected="true">?i=1;q=gloves</page>      
</pagination>

In the above example I need to pull out the total-pages node as an int and create an array of the page nodes. I have the basics of the deserializer working I just need to know how to set up my class to allow me to pull the array and int out. If I do the following in my main class:

[XmlArray("pagination")]
[XmlArrayItem("page", typeof(ResultsPage))]
public ResultsPage[] Pages { get; set; }
[XmlElement(ElementName = "total-pages")]
public int TotalPages { get; set; }

I get the array of the page nodes, but TotalPages is 0 and not 1. I have also tried the following in my main class:

[XmlElement(ElementName = "pagination")]
public Pagination Pagination { get; set; }

with a sub class

public class Pagination
{
    [XmlArray]
    [XmlArrayItem("page", typeof(ResultsPage))]
    public ResultsPage[] Pages { get; set; }
    [XmlElement(ElementName = "total-pages")]
    public int TotalPages { get; set; }
}

In that case the TotalPages is correctly set to 1, but the Pages array is null.

Is there a way to do this?

1 Answers1

1

This should work

public class Pagination
{
    [XmlElement("page")]
    public List<ResultsPage> Pages { get; set; }
    [XmlElement("total-pages")]
    public int TotalPages { get; set; }
}

public class ResultsPage
{
    [XmlAttribute("position")]
    public string Position;

    [XmlText]
    public string Text;
}

You only need to use XmlArray and XmlArrayItem attributes if you have a container element which you want to flatten. I.e.

<pagination>
    <total-pages>1</total-pages>
    <pages>
        <page position="first">?i=1;q=gloves</page>
        <page position="last">?i=1;q=gloves</page>
        <page position="1" selected="true">?i=1;q=gloves</page>      
    </pages>
</pagination>

Then you wold write

public class Pagination
{
    [XmlArray("pages"), XmlArrayItem("page")]
    public List<ResultsPage> Pages { get; set; }
    [XmlElement("total-pages")]
    public int TotalPages { get; set; }
}
Ilia G
  • 10,043
  • 2
  • 40
  • 59
  • @CynergyDigital but it changed your xml like I advised in my sample. This change is slightly different than mine, but it is a change! In your comment to my solution you've said, that you have no influence on xml, because it comes from 3rd party... – Fischermaen Oct 26 '11 at 17:23
  • @Fischermaen No, I downvoted your answer, because it is straight up wrong. The XML in my answer has nothing to do with the solution. It is simply an example to illustrate the case where he would need to use XmlArray attribute. – Ilia G Oct 26 '11 at 17:27