如何使用SoapFormatter类从C#.NET中的简单XML输出中获取SOAP包

时间:2017-02-15 14:20:49

标签: c# xml soap

我有以下FIX格式的输入(可能会根据要求改变)。我希望在SOAP信封中使用XML格式。我在C#中使用了SoapFormatter类,但输出错误。

输入:35 = U149 = GEMI18 = FIX.4.19 = 73256 = EMX

button_click() {

Dictionary<int, string> rawMessagedictionary = richTextBox1.Text.Split('\u0001').Select(part => part.Split('=')).Where(part => part.Length == 2).ToDictionary(sp => Convert.ToInt32(sp[0]), sp => sp[1]);
richTextBox2.Text = DictToXml(rawMessagedictionary, "messageTags", "tag").ToString();
  string soap= ObjectToSoapMessage(richTextBox2.Text);
  MessageBox.Show(soap);

}

// Method to Convert object message to SOAP format.

 public static string ObjectToSoapMessage(object messageString)
    {
        using (MemoryStream Stream = new MemoryStream())
        {
            SoapFormatter serializer = new SoapFormatter();
            serializer.Serialize(Stream, messageString);
            Stream.Flush();
            return UTF8Encoding.UTF8.GetString(Stream.GetBuffer(), 0, (int)Stream.Position);
        }
    }

// Code to convert FIX message to XML simple format 
public static XElement DictToXml
           (Dictionary<int, string> inputDict, string elmName, string valuesName)
    {

        XElement outElm = new XElement(elmName);

        Dictionary<int, string>.KeyCollection keys = inputDict.Keys;


        foreach (int key in keys)
        {
            XElement inner = new XElement(valuesName);
            inner.Add(new XAttribute("key", key));
            inner.Add(new XAttribute("value", inputDict[key]));
            outElm.Add(inner);

        }

        return outElm;

    }

输出如下:

    <messageTags>
<tag key="35" value="U1" />
<tag key="49" value="GEMI1" />
<tag key="8" value="FIX.4.1" />
<tag key="9" value="732" />
 <tag key="56" value="EMX" />
 </messageTags>

//

中输出错误
       string soap= ObjectToSoapMessage(richTextBox2.Text);
        MessageBox.Show(soap);

如下:

<SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<SOAP-ENC:string id="ref-1">&#60;messageTags&#62;
  &#60;tag key=&#34;35&#34; value=&#34;U1&#34; /&#62;
 &#60;tag key=&#34;49&#34; value=&#34;GEMI1&#34; /&#62;
 &#60;tag key=&#34;8&#34; value=&#34;FIX.4.1&#34; /&#62;
 &#60;tag key=&#34;9&#34; value=&#34;732&#34; /&#62;
   &#60;tag key=&#34;56&#34; value=&#34;EMX&#34; /&#62;
&#60;/messageTags&#62;</SOAP-ENC:string>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

为什么?输出采用这种格式..?

1 个答案:

答案 0 :(得分:0)

所以我认为有几种方法可以解决这个问题,一种方法是简单地做一个String.Replace("&#60;", "<")String.Replace("&#34;", "\"")String.Replace("&#62;", ">"),这或多或少是一个创可贴。你也可以使用XmlTextWriter and WriteRaw() method来防止输出转义字符而不是它们的字符重新定位