SOAP XML выберите узлы - PullRequest
       11

SOAP XML выберите узлы

0 голосов
/ 05 июля 2018

Я пытаюсь получить значения SOAP XML в объектах C #, но в настоящее время я не могу выбрать ни один узел и поэтому не получаю значения.

Это XML:

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<AddTwoStr xmlns="http://cpu1147/AB_TestWebApp/">
<InputParameters>
<Parameter>
<DataType>string</DataType>
<Name>String1</Name>
<Value>test</Value>
</Parameter>
<Parameter>
<DataType>string</DataType>
<Name>String2</Name>
<Value>test</Value
></Parameter>
</InputParameters>
</AddTwoStr>
</soap:Body>
</soap:Envelope>

XML хранится в следующем коде c #:

// Get raw request body
            Stream receiveStream = HttpContext.Current.Request.InputStream;
            // Move to begining of input stream and read
            receiveStream.Position = 0;
            //Webrequest als StreamReader
            //StreamReader mystream = new StreamReader(receiveStream, Encoding.UTF8);
            StreamReader mystream = new StreamReader(receiveStream);

            string test = mystream.ReadToEnd();

            XmlDocument document = new XmlDocument();
            document.LoadXml(test);

У кого-нибудь есть решение выбрать значения String1 и String2 ??

Спасибо и всего наилучшего, Chris

Ответы [ 2 ]

0 голосов
/ 08 июля 2018

Большое спасибо, что помогает. Теперь я могу ввести XML. Следующий вопрос - ответ. Я должен установить его как XML и попробовать следующее

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using System.Xml;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Web.Script.Services;
using System.Xml.Serialization;

namespace AB_TestWebApp
{
    /// <summary>
    /// Zusammenfassungsbeschreibung für WebService1
    /// </summary>
    [WebService(Namespace = "http://cpu1147/AB_TestWebApp/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(true)]
    // Wenn der Aufruf dieses Webdiensts aus einem Skript zulässig sein soll, heben Sie mithilfe von ASP.NET AJAX die Kommentarmarkierung für die folgende Zeile auf. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {


        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
        public string AddTwoStr()
        {
            //--//
            // Get raw request body
            Stream receiveStream = HttpContext.Current.Request.InputStream;
            // Move to begining of input stream and read
            receiveStream.Position = 0;
            //Webrequest als StreamReader
            //StreamReader mystream = new StreamReader(receiveStream, Encoding.UTF8);
            //StreamReader mystream = new StreamReader(receiveStream);

            //string test = mystream.ReadToEnd();

            //XmlDocument document = new XmlDocument();
            //document.LoadXml(test);
            //XElement xdocument = XElement.Parse(test);

            Envelope data;
            //var xml = document.Value;

            //using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(receiveStream.ToString())))
            using (StreamReader stream = new StreamReader(receiveStream, Encoding.UTF8))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
                data = (Envelope)serializer.Deserialize(stream);
            }

            //Access the parameters here via an index.
            string String1 = data.Body.AddTwoStr.InputParameters[0].Value;
            string String2 = data.Body.AddTwoStr.InputParameters[1].Value;

            //--//

            XElement sofon_response = new XElement("Parameter",
            new XElement("DataType", "String"),
            new XElement("Name", "WebResponse"),
            new XElement("Value", string.Concat(String1, String2))
            );

            return sofon_response.ToString();
        }


        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }


        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/", IsNullable = false)]
        public partial class Envelope
        {

            private EnvelopeBody bodyField;

            /// <remarks/>
            public EnvelopeBody Body
            {
                get
                {
                    return this.bodyField;
                }
                set
                {
                    this.bodyField = value;
                }
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public partial class EnvelopeBody
        {

            private AddTwoStrPar addTwoStrField;

            /// <remarks/>
            [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://cpu1147/AB_TestWebApp/")]
            public AddTwoStrPar AddTwoStr
            {
                get
                {
                    return this.addTwoStrField;
                }
                set
                {
                    this.addTwoStrField = value;
                }
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://cpu1147/AB_TestWebApp/")]
        [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://cpu1147/AB_TestWebApp/", IsNullable = false)]
        public partial class AddTwoStrPar
        {

            private AddTwoStrParameter[] inputParametersField;

            /// <remarks/>
            [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)]
            public AddTwoStrParameter[] InputParameters
            {
                get
                {
                    return this.inputParametersField;
                }
                set
                {
                    this.inputParametersField = value;
                }
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://cpu1147/AB_TestWebApp/")]
        public partial class AddTwoStrParameter
        {

            private string dataTypeField;

            private string nameField;

            private string valueField;

            /// <remarks/>
            public string DataType
            {
                get
                {
                    return this.dataTypeField;
                }
                set
                {
                    this.dataTypeField = value;
                }
            }

            /// <remarks/>
            public string Name
            {
                get
                {
                    return this.nameField;
                }
                set
                {
                    this.nameField = value;
                }
            }

            /// <remarks/>
            public string Value
            {
                get
                {
                    return this.valueField;
                }
                set
                {
                    this.valueField = value;
                }
            }
        }
    }
}

Моя проблема сейчас в том, что XML теперь не отформатирован, см. Этот пример:

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><AddTwoStrResponse xmlns="http://cpu1147/AB_TestWebApp/"><AddTwoStrResult>&lt;Parameter&gt;
  &lt;DataType&gt;String&lt;/DataType&gt;
  &lt;Name&gt;WebResponse&lt;/Name&gt;
  &lt;Value&gt;HalloChristian&lt;/Value&gt;
&lt;/Parameter&gt;</AddTwoStrResult></AddTwoStrResponse></soap:Body></soap:Envelope>

Что мне нужно вернуть, так это:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <WebMethodResponse xmlns="http://tempuri.org/">
            <WebMethodResult>
                <Parameter>
                    <DataType>String</DataType>
                    <Name>WebResponse</Name>
                    <Value>Hallo World</Value>
                </Parameter>
            </WebMethodResult>
        </WebMethodResponse>
        <soap:Fault>
            <faultcode/>
            <faultstring/>
            <faultactor/>
            <detail/>
        </soap:Fault>
    </soap:Body>
</soap:Envelope>

Я пытался десервализовать несколько раз, но я всегда получаю сообщение об ошибке "неправильный символ в XML"

0 голосов
/ 05 июля 2018

По моему опыту, SOAP-запросы, поступающие по проводам, десериализуются в известные типы, которые обычно предоставляются справочной информацией по потребляемым сервисам, которая генерируется при добавлении справочной службы. Я ценю, что вы потенциально могли бы получать эту полезную нагрузку из других мест, но я все еще нахожу, что часто проще использовать строго типизированные классы, чтобы помочь извлечь нужные значения. Конечно, вы можете загрузить XML-документ в документ XPath или что-то в этом роде и обойти узлы и элементы внутри.

В приведенном ниже примере я взял ваш xml и создал классы, необходимые для десериализации.

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/", IsNullable = false)]
    public partial class Envelope
    {

        private EnvelopeBody bodyField;

        /// <remarks/>
        public EnvelopeBody Body
        {
            get
            {
                return this.bodyField;
            }
            set
            {
                this.bodyField = value;
            }
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public partial class EnvelopeBody
    {

        private AddTwoStr addTwoStrField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://cpu1147/AB_TestWebApp/")]
        public AddTwoStr AddTwoStr
        {
            get
            {
                return this.addTwoStrField;
            }
            set
            {
                this.addTwoStrField = value;
            }
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://cpu1147/AB_TestWebApp/")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://cpu1147/AB_TestWebApp/", IsNullable = false)]
    public partial class AddTwoStr
    {

        private AddTwoStrParameter[] inputParametersField;

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)]
        public AddTwoStrParameter[] InputParameters
        {
            get
            {
                return this.inputParametersField;
            }
            set
            {
                this.inputParametersField = value;
            }
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://cpu1147/AB_TestWebApp/")]
    public partial class AddTwoStrParameter
    {

        private string dataTypeField;

        private string nameField;

        private string valueField;

        /// <remarks/>
        public string DataType
        {
            get
            {
                return this.dataTypeField;
            }
            set
            {
                this.dataTypeField = value;
            }
        }

        /// <remarks/>
        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        /// <remarks/>
        public string Value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }

Затем мы используем XMLSerializer для десериализации xml в экземпляр класса. В приведенном ниже примере я загрузил ваш xml из локального файла.

Envelope data;
var xml = File.ReadAllText(@"C:\test.xml");

 using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
 {
      XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
      data = (Envelope)serializer.Deserialize(stream);
 }

 //Access the parameters here via an index.
 var val = data.Body.AddTwoStr.InputParameters[0].Value;

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...