3

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Mike, this is in line with what I was expecting to use.
3

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

Comments

0

Here's what I have done before:

    private static string CreateXMLString(object o)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(object));
        var stringBuilder = new StringBuilder();
        using (var writer = XmlWriter.Create(stringBuilder))
        {
            serializer.Serialize(writer, o);
        }
        return stringBuilder.ToString();
    }

Comments

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.