开发者

Create XML string for Web Service

开发者 https://www.devze.com 2023-02-13 16:12 出处:网络
I am sending a request to a web service which requires a string containing XML, of which I have been giving an XSD.

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
            {
    开发者_如何学Python            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.


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.


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


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();
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号