Erick Araqelyan
Erick Araqelyan

Reputation: 3

Http Post request c# xml

How to write this type of request?

<?xml version="1.0" encoding="UTF-8"?>
<epolice>
    <request subject="push" action="register_number" id="4">
        <push cert_num="AA123456" pre="12" code="AA" post="345"/>
    </request>
    <signature>signature here</signature>
</epolice>

I don't know how to write request parameters of this type of struct.

Upvotes: 0

Views: 1807

Answers (1)

Ben
Ben

Reputation: 501

Fist make an object of your data

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace XmlSerialize
{
    [XmlRoot(ElementName="push")]
    public class Push {
        [XmlAttribute(AttributeName="cert_num")]
        public string Cert_num { get; set; }
        [XmlAttribute(AttributeName="pre")]
        public string Pre { get; set; }
        [XmlAttribute(AttributeName="code")]
        public string Code { get; set; }
        [XmlAttribute(AttributeName="post")]
        public string Post { get; set; }
    }

    [XmlRoot(ElementName="request")]
    public class Request {
        [XmlElement(ElementName="push")]
        public Push Push { get; set; }
        [XmlAttribute(AttributeName="subject")]
        public string Subject { get; set; }
        [XmlAttribute(AttributeName="action")]
        public string Action { get; set; }
        [XmlAttribute(AttributeName="id")]
        public string Id { get; set; }
    }

    [XmlRoot(ElementName="epolice")]
    public class Epolice {
        [XmlElement(ElementName="request")]
        public Request Request { get; set; }
        [XmlElement(ElementName="signature")]
        public string Signature { get; set; }
    }

}

Serialize

private static string XMLSerializer(object obj)
    {
        string xml = "";
        XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
        {
            Encoding = Encoding.UTF8,
            Indent = true
        };
        using (var sww = new Utf8StringWriter())
        {
            using (XmlWriter writer = XmlWriter.Create(sww, xmlWriterSettings))
            {
                    XmlSerializer serializer = new XmlSerializer(obj.GetType());
                    serializer.Serialize(writer, obj);
                xml = sww.ToString();
            }
        }
        return xml;
    }
    private sealed class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding { get { return Encoding.UTF8; } }
    }

Then you can post your xml serialized Look this example post

Upvotes: 3

Related Questions