我想将类Ticket
序列化为xml。我得到错误:" XmlAttribute / XmlText不能用于编码复杂类型"因为我的自定义类。
这就是自定义域的xml应该是这样的(属性数组是nesseray但我不了解如何创建它):
<custom_fields type="array">
<custom_field name="Standby Reason" id="6">
<value/>
</custom_field>
<custom_field name="Close Date" id="84">
班级门票
public class Ticket
{
[XmlElement("custom_fields")]
public CustomFields Custom_fields { get; set; }
Class CustomFields
[Serializable]
public class CustomFields
{
[XmlAttribute("array")]
public List<CustomField> custom_field { get; set; }
Class CustomField
[Serializable]
public class CustomField
{
[XmlIgnore]
public string Name { get; set; }
[XmlElement]
public int Id { get; set; }
[XmlElement]
public string Value { get; set; }
序列化方法
public string Serialize(object obj)
{
var nsSerializer = new XmlSerializerNamespaces();
nsSerializer.Add(String.Empty, String.Empty);
var serializer = new XmlSerializer(typeof(Ticket), String.Empty);
using (StringWriter writer = new StringWriter())
{
ExtendedXmlTextWriter xmlTextWriter = new ExtendedXmlTextWriter(writer);
serializer.Serialize(xmlTextWriter, obj, nsSerializer);
//return writer.ToString();
XElement root = new XElement("custom_fields", new XAttribute("type", "array"),
new XElement("custom_field",
new XAttribute("name", "Standby Reason"),
new XAttribute("id", 6)
), new XElement("value"),
new XElement("custom_field",
new XAttribute("name", "Close Date"),
new XAttribute("id", 84)
)
);
return (writer.ToString() + root.ToString());
}
答案 0 :(得分:5)
有时Linq To Xml非常有帮助
XElement root = new XElement("ticket",
new XElement("custom_fields",
new XAttribute("type", "array"),
new XElement("custom_field",
new XAttribute("name", "Standby Reason"),
new XAttribute("id", 6)
),
new XElement("value"),
new XElement("custom_field",
new XAttribute("name", "Close Date"),
new XAttribute("id", 84)
)
)
);
string xml = root.ToString();
输出:
<ticket>
<custom_fields type="array">
<custom_field name="Standby Reason" id="6" />
<value />
<custom_field name="Close Date" id="84" />
</custom_fields>
</ticket>
答案 1 :(得分:1)
班级门票
public class Ticket
{
[XmlElement("custom_fields")]
public CustomFields Custom_fields { get; set; }
Class CustomFields
[Serializable]
public class CustomFields
{
[XmlArray("array"), XmlArrayItem("custom_field")]
public List<CustomField> custom_field { get; set; }
Class CustomField
[Serializable]
public class CustomField
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("value")]
public string Value { get; set; }
XML:
<ticket>
<custom_fields>
<array>
<custom_field name="Standby Reason" id="6"><value /></custom_field>
<custom_field name="Close Date" id="84"><value /></custom_field>
</array>
</custom_fields>
</ticket>
答案 2 :(得分:0)
列表与LT;&的CustomField GT;不能是XML属性。