balaji
balaji

Reputation: 1304

Add root element attribute

I'm serializing a class like below

 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()

The result string below

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

but, How can i add an attribute to the root element(Response)? like below one

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

Upvotes: 0

Views: 5553

Answers (2)

Nate
Nate

Reputation: 661

You can create another object that contains the list, and then create a property to add the attribute to the root node.

The trick is to preface the list in this new class with an explicit type assignment to the Student type to avoid having your list nested within another parent node.

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

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

Your code would then look like the following

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()

Upvotes: 1

RobJohnson
RobJohnson

Reputation: 885

You just need to mark that property of the class with XmlAttribute, i.e.

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

Edit:

Just realised you are serializing the list directly. Put your list inside a parent class, Response, and add the above attribute to this Response class, then serialise the Response object.

Hope this helps.

Upvotes: 3

Related Questions