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...?

6
  • 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. Commented Dec 4, 2013 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 ? Commented Dec 4, 2013 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? Commented Dec 4, 2013 at 10:27
  • I return a the XmlDocument from the web service as a XmlDocument type Commented Dec 4, 2013 at 10:28
  • Maybe this would help: C# XML Insert comment into XML after xml tag Commented Dec 4, 2013 at 11:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.