Creating an XML String for a Web Service

I am sending a request to a web service that requires a string containing XML from which I am providing XSD.

I ran xsd.exe and created a class based on this, but not sure if the best way is to create an xml string to send, such as a stream, XMLDocument, or some form of serialization.

UPDATE

I found here 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 allows me to control the tag attribute.

+3
source share
3 answers

What I do several times is to create a class / structure for storing data in the client program and serializing the data as a string. Then I make a web request and send it to an XML string. Here is the code that I use to serialize the object into 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;
}

, .

+4

Xstream framework xml. , !

+3

Here is what I did 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();
    }
0
source

Source: https://habr.com/ru/post/1794741/


All Articles