2

I have the following class;

[XmlRoot("Customer")]
public class MyClass
{
    [XmlElement("CustId")]
    public int Id {get;set;}

    [XmlElement("CustName")]
    public string Name {get;set;}
}

I then use the following function serialise the class object to Xml

public static XmlDocument SerializeObjectToXML(object obj, string sElementName)
 {
    XmlSerializer serializer = 
          new XmlSerializer(obj.GetType(), new XmlRootAttribute("Response"));

    using (MemoryStream ms = new MemoryStream())
    {
       XmlDocument xmlDoc = new XmlDocument();
       serializer.Serialize(ms, obj);
       ms.Position = 0;
       xmlDoc.Load(ms);
    }
}

My current output to XML is like;

<Response>
  <CustId></CustId>
  <CustName></CustName>
</Response>

However I'd like to add a comment like

<Response>
  <CustId></CustId>
  <CustName></CustName>
</Response>
<!-- Sample Comment Here -->

How can I achieve this ? I tried the following;

XmlComment xmlComment;
xmlComment = xmlDoc.CreateComment("Sample XML document");

XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertAfter(xmlComment, root);

But, when I try to read the Xml using this kind of WebClient call

oClient.UploadString("http://www.myurl.com/", "POST", "");

I can see the Xml elements, but not the comment.

UPDATE

I checked, and even if I call the webservice (ASMX) directly via a browser, the comment tag is NOT returned when using the browser developer Tools.

It would appear that the ASMX webservice is not returning the comment tag...?

neildt
  • 5,101
  • 10
  • 56
  • 107
  • As far as I see, there is no way of serializing comments using `XmlSerializer`. It has no mechanism (again, none that I know of) for saving the comments. – Andrei V Dec 04 '13 at 10:22
  • By appending the comment like above it does work, and if I debug the code can see the comment in the InnerXml property. But for some reason when reading using the WebClient, I can't see the comment, any ideas why ? – neildt Dec 04 '13 at 10:25
  • How do you assemble the string that you transmit to the web Service? Can you analyze the request with Fiddler and check whether the comment is present there? – Markus Dec 04 '13 at 10:27
  • I return a the XmlDocument from the web service as a XmlDocument type – neildt Dec 04 '13 at 10:28
  • Maybe this would help: [C# XML Insert comment into XML after xml tag](http://stackoverflow.com/questions/7385921/how-to-write-a-comment-to-an-xml-file-when-using-the-xmlserializer) – IDeveloper Dec 04 '13 at 11:02
  • This is kind of what I require, but my requirement is to add the comment at the bottom of the XmlDocument, as it will also contain some timestamp information. – neildt Dec 04 '13 at 11:14

0 Answers0