Как добавить атрибуты для С# XML Serialization
У меня проблема с сериализацией и объектом, я могу заставить его создать все правильные выходные данные, кроме тех случаев, когда у меня есть элемент, которому требуется значение и атрибут. Вот требуемый вывод:
<Root>
<Method>Retrieve</Method>
<Options>
<Filter>
<Times>
<TimeFrom>2009-06-17</TimeFrom>
</Times>
<Document type="word">document name</Document>
</Filter>
</Options>
</AdCourierAPI>
Я могу создать все это, но не могу найти способ установить атрибут типа Document, вот сегмент класса объекта
[XmlRoot("Root"), Serializable]
public class Root
{
[XmlElement("Method")]
public string method="RetrieveApplications";
[XmlElement("Options")]
public _Options Options;
}
public class _Options
{
[XmlElement("Filter")]
public _Filter Filter;
}
public class _Filter
{
[XmlElement("Times")]
public _Times Times;
[XmlElement("Documents")]
public string Documents;
}
который дает мне:
<Document>document name</Document>
а не:
<Document type="word">document name</Document>
но я не могу найти способ исправить это, пожалуйста, сообщите.
Спасибо
Ответы
Ответ 1
Где хранится type
?
Обычно вы можете иметь что-то вроде:
class Document {
[XmlAttribute("type")]
public string Type { get; set; }
[XmlText]
public string Name { get; set; }
}
public class _Filter
{
[XmlElement("Times")]
public _Times Times;
[XmlElement("Document")]
public Document Document;
}
Ответ 2
Класс string
не имеет свойства type
, поэтому вы не можете использовать его для создания желаемого результата. Вместо этого вы должны создать класс Document
:
public class Document
{
[XmlText]
public string Name;
[XmlAttribute("type")]
public string Type;
}
И вы должны изменить свойство Document
, чтобы ввести Document
Ответ 3
Похоже, вам нужен дополнительный класс:
public class Document
{
[XmlAttribute("type")]
public string Type { get; set; }
[XmlText]
public string Name { get; set; }
}
Если экземпляр (в примере) имел бы Type = "word"
и Name = "document name"
; documents
будет List<Document>
.
Кстати, публичные поля редко бывают хорошей идеей...