0

我正在序列化一个像下面这样的类

 XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
 namespaces.Add(string.Empty, string.Empty);
 StringWriter sw = new StringWriter();
 XmlSerializer serializer1 = new XmlSerializer(typeof(List<student>), new XmlRootAttribute("Response"));
 XmlTextWriter xmlWriter = new XmlTextWriter(sw);
 serializer1.Serialize(xmlWriter, ls, namespaces);
 sw.ToString()

下面的结果字符串

<?xml version="1.0" encoding="utf-16"?>
<Response><student><name>xxx</name></student></Response>

但是,如何向根元素(响应)添加属性?像下面一个

<?xml version="1.0" encoding="utf-16"?>
<Response status="1"><student><name>xxx</name></student></Response>
4

2 回答 2

3

您只需要使用 XmlAttribute 标记该类的属性,即

class MyClass{
[XmlAttribute("status")]
public string ErrorStatus { get; set; }
}

编辑:

刚刚意识到您正在直接序列化列表。将您的列表放入父类 Response 中,并将上述属性添加到此 Response 类,然后序列化 Response 对象。

希望这可以帮助。

于 2013-03-12T09:43:01.470 回答
1

您可以创建另一个包含该列表的对象,然后创建一个属性以将该属性添加到根节点。

诀窍是在这个新类中的列表前加上对 Student 类型的显式类型分配,以避免将列表嵌套在另一个父节点中。

[XmlType(TypeName = "Response")]    
public class ResponseObject
{
    [XmlAttribute("status")]        
    public string file { get; set; }

    [XmlElement("Student", Type = typeof(Student))]
    public List<Student> studentList { get; set; }
}

您的代码将如下所示

XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
StringWriter sw = new StringWriter();
XmlSerializer serializer1 = new XmlSerializer(typeof(ResponseObject));
XmlTextWriter xmlWriter = new XmlTextWriter(sw);

//Creating new object and assign the existing list and status
ResponseObject resp = new ResponseObject();
resp.studentList = ls;
resp.status = 1;

//Serialize with the new object
serializer1.Serialize(xmlWriter, resp, namespaces);
sw.ToString()
于 2013-03-15T21:51:04.893 回答