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?
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. Ie
<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; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.