關於寫xml字符串的一些積累

最近在項目中用到用xml模擬post提交的問題,一開始着實蒙了不知道怎麼寫xml文件,根據自己的一些經驗,總結下來一些常用的xml寫法,有許多不好的地方還請幫我多多改正!現在上代碼了
</pre><pre class="csharp" name="code">  private static void WriteXmlHeader(XmlWriter xmlTextWriter)
        {
            xmlTextWriter.WriteStartElement("s", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
            xmlTextWriter.WriteStartElement("s", "Body", null);
            xmlTextWriter.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
            xmlTextWriter.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
            xmlTextWriter.WriteStartElement("", "getTransportWayList", "http://service.hop.service.ws.hlt.com/");
            xmlTextWriter.WriteStartElement("userToken", "");
            xmlTextWriter.WriteValue("password");
            xmlTextWriter.WriteEndElement();

            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteEndElement();
        }


private static void WriteElement(XmlTextWriter writer, string name, string value)
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                writer.WriteElementString(name, value);
            }
        }

這部分是寫頭部部分的,寫出來的結果是這樣子的
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><getTransportWayList xmlns="http://service.hop.service.ws.hlt.com/"><userToken xmlns="">password</userToken></getTransportWayList></s:Body></s:Envelope>

這些都是比較基本的,可以看到,寫出來的xml是沒有xml聲明的,而xml文件開頭處的聲明,我們也是可以自己選擇要不要的,有時候還是默認utf-16的,就比如這樣

     private static void WriteXmlTest()
        {
            using (StringWriter stringWriter = new StringWriter())
            {
                //  XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);  //沒有前面的utf-8
                XmlWriter xmlTextWriter = XmlWriter.Create(stringWriter);   //有xml前面的申明,默認utf-16
               // xmlTextWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");    //自定義xml申明部分
                xmlTextWriter.WriteStartElement("soap", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
                xmlTextWriter.WriteAttributeString("xmlns", "soapenc", null, "http://schemas.xmlsoap.org/soap/encoding/");
                xmlTextWriter.WriteAttributeString("xmlns", "tns", null, "http://edpost.vekinerp.com/soap/ecpp_wsdl");
                xmlTextWriter.WriteAttributeString("xmlns", "types", null, "http://edpost.vekinerp.com/soap/ecpp_wsdl/encodedTypes");
                xmlTextWriter.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                xmlTextWriter.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");

                xmlTextWriter.WriteStartElement("soap", "Body", null);
                xmlTextWriter.WriteAttributeString("soap", "encodingStyle", null, "http://schemas.xmlsoap.org/soap/encoding/");

                xmlTextWriter.WriteStartElement("addOrder", "");

                WriteElementExt(xmlTextWriter, "token", "xsi", "type", "xsd:string", "324324234");
                WriteElementExt(xmlTextWriter, "orderInfo", "", "href", "#id1");
                WriteElementExt(xmlTextWriter, "orderGoodsInfo", "", "href", "#id2");
                xmlTextWriter.WriteEndElement();

                xmlTextWriter.WriteStartElement("tns", "Body", null);
                xmlTextWriter.WriteAttributeString("", "id", null, "id1");
                xmlTextWriter.WriteAttributeString("xsi", "type", null, "tns:orderInfo");
                WriteElementExt(xmlTextWriter, "paypalid", "xsi", "type", "xsd:string", "211313");
                WriteElementExt(xmlTextWriter, "street1", "xsi", "type", "xsd:string", "fdfsfd");
                WriteElementExt(xmlTextWriter, "pay_note", "xsi", "type", "xsd:string", "備註");   //支付備註
                xmlTextWriter.WriteEndElement();

                xmlTextWriter.WriteEndElement();
                xmlTextWriter.WriteEndElement();
                xmlTextWriter.Flush();
                xmlTextWriter.Close();
                Console.WriteLine(stringWriter.ToString());
                Console.Read();
            }
        }

        /// <summary>
        /// 寫xml元素
        /// </summary>
        /// <param name="writer">xml寫</param>
        /// <param name="name">元素名字</param>
        /// <param name="preFix">元素前綴</param>
        /// <param name="ns">元素命名</param>
        /// <param name="url">對應的空間</param>
        /// <param name="value">對應值</param>
        private static void WriteElementExt(XmlWriter writer, string name, string preFix, string ns, string url, string value = "")
        {
            writer.WriteStartElement(name);
            writer.WriteAttributeString(preFix, ns, null, url);
            if (!string.IsNullOrWhiteSpace(value))
                writer.WriteNmToken(value);
            writer.WriteEndElement();
        }

這一段代碼打印出來的結果是這樣的


<?xml version="1.0" encoding="utf-16"?><soap:Envelope xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://edpost.vekinerp.com/soap/ecpp_wsdl" xmlns:types="http://edpost.vekinerp.com/soap/ecpp_wsdl/encodedTypes" 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 soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><addOrder><token xsi:type="xsd:string">324324234</token><orderInfo href="#id1" /><orderGoodsInfo href="#id2" /></addOrder><tns:Body id="id1" xsi:type="tns:orderInfo"><paypalid xsi:type="xsd:string">211313</paypalid><street1 xsi:type="xsd:string">fdfsfd</street1><pay_note xsi:type="xsd:string">備註</pay_note></tns:Body></soap:Body></soap:Envelope>


裏面可能有很多還可以改進的地方,不過目前我還沒有找到,現學現賣!希望能夠幫助到你們,也是對自己知識的一個積累(哪天要用上的直接拿下來),後面的post提交,應該就容易了。

  using (WebClient webClient = new WebClient())
            {
                string result = string.Empty;
                webClient.Headers[HttpRequestHeader.ContentType] = "text/xml; charset=utf-8";
                webClient.Headers["SOAPAction"] = "http://tempuri.org/GET_FREIGHT_WAY";
                result = Encoding.UTF8.GetString(webClient.UploadData(LogisticsWayUrl, "POST", Encoding.UTF8.GetBytes(xmlData)));
                if (!string.IsNullOrWhiteSpace(result))
                {
                    XmlDocument document = new XmlDocument();
                    document.LoadXml(result);
                    XmlNamespaceManager nmarager = new XmlNamespaceManager(document.NameTable);
                    nmarager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
                    nmarager.AddNamespace("a", "http://tempuri.org/");

                    XmlNode FreightWayInfoList;
                    XmlNode GET_FREIGHT_WAYResponse = document.SelectSingleNode("/soap:Envelope/soap:Body/a:GET_FREIGHT_WAYResponse", nmarager);
                    FreightWayInfoList = GET_FREIGHT_WAYResponse.FirstChild.FirstChild.FirstChild;
                    List<LogisticsChannel> channelList = new List<LogisticsChannel>();
                    foreach (XmlNode xnS in FreightWayInfoList.ChildNodes)
                    {
                        string value = xnS.SelectSingleNode("FreightWayId").InnerText;
                        string name = xnS.SelectSingleNode("FreightWayName_CN").InnerText;
                        channelList.Add(new LogisticsChannel(name, value));
                    }
                    return channelList.ToArray<LogisticsChannel>();
                }

下面的那些是提交之後得到的xml頁,從中提取數據,在這裏推薦大家可以用Fiddler這個工具來抓包玩玩


那段result就是根據xml文檔來讀取到FreightWayId和FreightWayName_CN的。


剛剛看了一下,結果顯示的那些代碼貼上去是html格式的,最好運行一下的出來的纔是正確的結果! 汗





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章