Answer the question
In order to leave comments, you need to log in
Desearilizing an array of objects from an XML document without a wrapper
There is the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<issue_statuses>
<issue_status>
<id>1</id>
<name>Новый</name>
<is_default>true</is_default>
<is_closed>false</is_closed>
</issue_status>
<issue_status>
<id>2</id>
<name>Назначен</name>
<is_default>false</is_default>
<is_closed>false</is_closed>
</issue_status>
</issue_statuses>
public class IssueStatus
{
[XmlElement("id")]
public int Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("is_default")]
public bool IsDefault { get; set; }
[XmlElement("is_closed")]
public bool IsClosed { get; set; }
}
// Бесполезный класс-обертка
[XmlRoot("issue_statuses")]
public class IssueStatuses
{
[XmlElement("issue_status")]
public IssueStatus[] items;
}
// Получаем нужное
private static IssueStatus[] GetIssueStatuses()
{
IssueStatuses statuses;
using (var txtReader = new StreamReader(@"statuses.xml"))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(IssueStatuses));
statuses = (IssueStatuses)xmlSerializer.Deserialize(txtReader);
}
Console.WriteLine(statuses.items.Length);
return statuses.items;
}
Answer the question
In order to leave comments, you need to log in
using (var txtReader = new StreamReader(@"statuses.xml")) {
var xmlAttributeOverrides = new XmlAttributeOverrides();
var xmlAttributes = new XmlAttributes {
XmlRoot = new XmlRootAttribute("issue_statuses")
};
xmlAttributeOverrides.Add(typeof(IssueStatus[]), xmlAttributes);
var attributes = new XmlAttributes {
XmlRoot = new XmlRootAttribute("issue_status"),
XmlType = new XmlTypeAttribute("issue_status")
};
xmlAttributeOverrides.Add(typeof(IssueStatus), attributes);
var xmlSerializer = new XmlSerializer(typeof (IssueStatus[]), xmlAttributeOverrides);
var statuses = (IssueStatus[])xmlSerializer.Deserialize(txtReader);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question