Paul McCowat Paul McCowat - 9 months ago 54
C# Question

Create XML string for Web Service

I am sending a request to a web service which requires a string containing XML, of which I have been giving an XSD.

I've ran xsd.exe and created a class based on this but am unsure of the best way to create the xml string to send, for example a stream, XMLDocument or some form of serialization.


I found this here

public static string XmlSerialize(object o)
using (var stringWriter = new StringWriter())
var settings = new XmlWriterSettings
Encoding = Encoding.GetEncoding(1252),
OmitXmlDeclaration = true
using (var writer = XmlWriter.Create(stringWriter, settings))
var xmlSerializer = new XmlSerializer(o.GetType());
xmlSerializer.Serialize(writer, o);
return stringWriter.ToString();

which lets me control the tag attribute.

Thanks to all who helped.

Answer Source

What I am doing on several occasions is creating a class/struct to hold the data on the client-side program and serializing the data as a string. Then I make the web request and send it that XML string. Here is the code I use to serialize an object to XML:

public static string SerializeToString(object o)
    string serialized = "";
    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    //Serialize to memory stream
    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(o.GetType());
    System.IO.TextWriter w = new System.IO.StringWriter(sb);
    ser.Serialize(w, o);

    //Read to string
    serialized = sb.ToString();
    return serialized;

As long as all the contents of the object are serializable it will serialize any object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download