L
L
LastDragon2013-12-10 20:09:21
C++ / C#
LastDragon, 2013-12-10 20:09:21

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>

Task: get objects of type from it:
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; }
}

Option: This can be done like this:
// Бесполезный класс-обертка
[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;
}

Question: Is it possible to somehow get rid of the useless IssueStatuses wrapper and get IssueStatus[] right away?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Glebov, 2013-12-11
@LastDragon

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 question

Ask a Question

731 491 924 answers to any question