在我正在开发的项目中,我已经获得了XML,我无法控制。我需要提取一个节点数组以及一个奇异的属性,它是数组的兄弟。 (参见下面的示例XML)
<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>
在上面的示例中,我需要将total-pages节点作为int拉出并创建页面节点的数组。我有解串器工作的基础知识我只需要知道如何设置我的类以允许我拉出数组和int。如果我在我的主要课程中执行以下操作:
[XmlArray("pagination")]
[XmlArrayItem("page", typeof(ResultsPage))]
public ResultsPage[] Pages { get; set; }
[XmlElement(ElementName = "total-pages")]
public int TotalPages { get; set; }
我得到了页面节点的数组,但TotalPages是0而不是1.我还在我的主类中尝试了以下内容:
[XmlElement(ElementName = "pagination")]
public Pagination Pagination { get; set; }
带有子类
public class Pagination
{
[XmlArray]
[XmlArrayItem("page", typeof(ResultsPage))]
public ResultsPage[] Pages { get; set; }
[XmlElement(ElementName = "total-pages")]
public int TotalPages { get; set; }
}
在这种情况下,TotalPages正确设置为1,但Pages数组为空。
有办法做到这一点吗?
答案 0 :(得分:1)
这应该有效
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;
}
如果您有一个要展平的容器元素,则只需要使用XmlArray和XmlArrayItem属性。即。
<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>
然后你写了
public class Pagination
{
[XmlArray("pages"), XmlArrayItem("page")]
public List<ResultsPage> Pages { get; set; }
[XmlElement("total-pages")]
public int TotalPages { get; set; }
}