Проблема с консольным приложением с ядром .net, которое использует мыльный веб-сервис - PullRequest
0 голосов
/ 26 апреля 2019

Я новичок в ядре .net и пытаюсь создать консольное приложение, которое использует веб-сервис SOAP в моем проекте ядра .net. Я искал библиотеки, но не мог их найти. Я начал писать код и получил его в точке, где я могу получить XML из запроса SOAP. Моя проблема в том, что мой код, который печатает весь XML в виде простого текста, не очень удобен. Я пытаюсь получить доступ к своим данным в XML, но безуспешно.

Я делаю это слишком сложно? Есть ли способ или библиотека для использования, которая делает это проще?

/// <summary>
        /// Execute a Soap WebService call
        /// </summary>
        public static void Execute()
        {
            HttpWebRequest request = CreateWebRequest();
            XmlDocument soapEnvelopeXml = new XmlDocument();
            soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
                <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:GET-AG=""http://ortsinfoV13x0.stromgas.services.getag.com"">
                <soapenv:Header></soapenv:Header>
                <soapenv:Body>
                <GET-AG:getOrteByPlz>
                    <GET-AG:rec>
                        <GET-AG:auth_LoginName>----------</GET-AG:auth_LoginName>
                        <GET-AG:auth_Passwort>------</GET-AG:auth_Passwort>
                    </GET-AG:rec>
                <GET-AG:plz>69126</GET-AG:plz>
                </GET-AG:getOrteByPlz>
                </soapenv:Body>
                </soapenv:Envelope>"
            );

            using (Stream stream = request.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }

            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    string soapResult = rd.ReadToEnd();
                    Console.WriteLine(soapResult);
                }
            }
        }
        /// <summary>
        /// Create a soap webrequest to [Url]
        /// </summary>
        /// <returns></returns>
        public static HttpWebRequest CreateWebRequest()
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"----------");
            webRequest.Headers.Add(@"SOAP:Action");
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            return webRequest;
        }

        static void Main(string[] args)
        {
            Execute();
        }


Это XML:

<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <ns:getOrteByPlzResponse xmlns:ns="----------">
            <ns:return xmlns:ax215="----------" xmlns:ax213="----------" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ax213:Adressinfo">
                <ax213:fehlerCode>1</ax213:fehlerCode>
                <ax213:fehlerMeldungLength>0</ax213:fehlerMeldungLength>
                <ax213:input xsi:type="ax213:AdressinfoParameter">
                    <ax213:strassenRequest xsi:nil="true"/>
                    <ax213:stringRequest>69126</ax213:stringRequest>
                    <ax213:validationsRequest xsi:nil="true"/>
                </ax213:input>
                <ax213:itag>BPTest1;;26.04.2019,15:16:21</ax213:itag>
                <ax213:ort xsi:type="ax213:Ort">
                    <ax213:alort>22810500</ax213:alort>
                    <ax213:gkz>08221000</ax213:gkz>
                    <ax213:ortsname>Heidelberg</ax213:ortsname>
                    <ax213:ortsteil>Boxberg</ax213:ortsteil>
                    <ax213:ortsteil>Emmertsgrund</ax213:ortsteil>
                    <ax213:ortsteil>Rohrbach</ax213:ortsteil>
                    <ax213:ortsteil>Südstadt</ax213:ortsteil>
                    <ax213:ortsteilLength>4</ax213:ortsteilLength>
                    <ax213:plzLength>0</ax213:plzLength>
                </ax213:ort>
                <ax213:ortLength>1</ax213:ortLength>
                <ax213:strasseLength>0</ax213:strasseLength>
                <ax213:validation xsi:nil="true"/>
            </ns:return>
        </ns:getOrteByPlzResponse>
    </soapenv:Body>
</soapenv:Envelope>

Ответы [ 2 ]

1 голос
/ 26 апреля 2019

Для простого и быстрого доступа к значениям вы можете использовать XmlReader для чтения ответа SOAP, чтобы найти сопоставления LocalName / Value от каждого XmlElement, а затем сохранить результаты в NameValueCollection (илинезависимо от того, ICollection вы предпочитаете):

public static void Main()
{
    string strResponse = "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\r\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n    <soapenv:Body>\r\n        <ns:getOrteByPlzResponse xmlns:ns=\"----------\">\r\n            <ns:return xmlns:ax215=\"----------\" xmlns:ax213=\"----------\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ax213:Adressinfo\">\r\n                <ax213:fehlerCode>1</ax213:fehlerCode>\r\n                <ax213:fehlerMeldungLength>0</ax213:fehlerMeldungLength>\r\n                <ax213:input xsi:type=\"ax213:AdressinfoParameter\">\r\n                    <ax213:strassenRequest xsi:nil=\"true\"/>\r\n                    <ax213:stringRequest>69126</ax213:stringRequest>\r\n                    <ax213:validationsRequest xsi:nil=\"true\"/>\r\n                </ax213:input>\r\n                <ax213:itag>BPTest1;;26.04.2019,15:16:21</ax213:itag>\r\n                <ax213:ort xsi:type=\"ax213:Ort\">\r\n                    <ax213:alort>22810500</ax213:alort>\r\n                    <ax213:gkz>08221000</ax213:gkz>\r\n                    <ax213:ortsname>Heidelberg</ax213:ortsname>\r\n                    <ax213:ortsteil>Boxberg</ax213:ortsteil>\r\n                    <ax213:ortsteil>Emmertsgrund</ax213:ortsteil>\r\n                    <ax213:ortsteil>Rohrbach</ax213:ortsteil>\r\n                    <ax213:ortsteil>Südstadt</ax213:ortsteil>\r\n                    <ax213:ortsteilLength>4</ax213:ortsteilLength>\r\n                    <ax213:plzLength>0</ax213:plzLength>\r\n                </ax213:ort>\r\n                <ax213:ortLength>1</ax213:ortLength>\r\n                <ax213:strasseLength>0</ax213:strasseLength>\r\n                <ax213:validation xsi:nil=\"true\"/>\r\n            </ns:return>\r\n        </ns:getOrteByPlzResponse>\r\n    </soapenv:Body>\r\n</soapenv:Envelope>";
    NameValueCollection nameValueCollection = new NameValueCollection();
    try
    {
        using (StringReader stringReader = new StringReader(strResponse))
        {
            using (XmlReader xmlReader = XmlReader.Create(stringReader, new XmlReaderSettings()))
            {
                xmlReader.MoveToContent();

                string strKeyValue = null;
                do
                {
                    switch (xmlReader.NodeType)
                    {
                        case XmlNodeType.Text:
                            strKeyValue = xmlReader.Value;
                            break;

                        case XmlNodeType.EndElement:
                            if (!string.IsNullOrEmpty(strKeyValue))
                            {
                                nameValueCollection.Add(xmlReader.LocalName, strKeyValue);
                            }
                            break;

                        default:
                            strKeyValue = null;
                            break;
                    }
                } while (xmlReader.Read());
            }
        }
    }
    catch (Exception parentException)
    {
        Console.WriteLine(parentException);
    }
}

Чтобы получить строковое значение для любого XmlElement, вам необходимо получить доступ к NameValueCollection по известному ключу (без префикса пространства имен).Например:

nameValueCollection["fehlerCode"]

Пример вывода AllKeys и значений:

Console.Write(string.Join(Environment.NewLine, nameValueCollection.AllKeys.Select(x => x + ": " + nameValueCollection[x])));

fehlerCode: 1
fehlerMeldungLength: 0
stringRequest: 69126
itag: BPTest1;;26.04.2019,15:16:21
alort: 22810500
gkz: 08221000
ortsname: Heidelberg
ortsteil: Boxberg,Emmertsgrund,Rohrbach,Südstadt
ortsteilLength: 4
plzLength: 0
ortLength: 1
strasseLength: 0
0 голосов
/ 26 апреля 2019

Следующий код хорошо распечатает все

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication110
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement rtn = doc.Descendants().Where(x => x.Name.LocalName == "return").FirstOrDefault();
            string output = "";
            foreach (XElement child in rtn.Descendants())
            {
                string name = child.Name.LocalName;
                if (name.Contains("validation"))
                {
                    string nil = child.Attributes().First().Value;
                    output = name + " : " + nil;
                }
                else
                {
                    output = name + " : " + (string)child;
                }
                Console.WriteLine(output);
            }
            Console.ReadLine();
        }
    }
}
...