Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

UPDATE

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.

like image 819
PMC Avatar asked May 22 '26 18:05

PMC


2 Answers

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);
    w.Close();

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

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

like image 129
Mike Webb Avatar answered May 25 '26 08:05

Mike Webb


Use Xstream framework to generate an xml string. Hope this helps!

like image 34
jqueryEnthusiast Avatar answered May 25 '26 07:05

jqueryEnthusiast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!