Thursday 13 June 2019

MVC - Web Service - Create Web Service - Pass XML as Parameter and Receive XML in Web Service


Pass xml file (created on the fly) to web service

Watch this example on YouTube


 
1. Publisher

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;

namespace WebApplication13
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public string TextXML(string xmlFile)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlFile);
            // here do whatever you want with xml file
            return "success";
        }
    }
}

2. Subscriber

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace WebApplication14.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            XmlNode usersNode = doc.CreateElement("Users");
            doc.AppendChild(usersNode);
            XmlNode userNode = doc.CreateElement("User");
            XmlAttribute userAttribute = doc.CreateAttribute("ID");
            userAttribute.Value = "1";
            usersNode.AppendChild(userNode);

            XmlNode nameNode = doc.CreateElement("Name");
            nameNode.AppendChild(doc.CreateTextNode("Frank"));
            userNode.AppendChild(nameNode);
            XmlNode addressNode = doc.CreateElement("Address");
            addressNode.AppendChild(doc.CreateTextNode("1 Main St."));
            userNode.AppendChild(addressNode);

            var XMLString = doc.InnerXml;

            localhost.WebService1 test = new localhost.WebService1();
            var res = test.TextXML(XMLString);

            return View();
        }

No comments:

Post a Comment