Serialize XmlDocument & send via HTTPWebRequest

删除回忆录丶 提交于 2019-12-01 09:37:16
Russell Troywest

I'm guessing this question is related to the previous one about 2 xml documents not being able to be combined into one document without wrapping them both in a root node first (C# XmlDocument Nodes).

If that is the case then you don't want to be serialising the XmlDocuments and sending them to the WebService. Serializing the objects is for transporting/storing the actual object, not the data. You want to just send the webservice the data not the object so just concatenate the two xml documents and send that.

use XmlDocument.OuterXml to get the XmlDocument as a string. ie:

XmlDocument doc1 = new XmlDocument();
doc.LoadXml("Some XML");
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml("Some other XML");
StringBuilder sb = new StringBuilder();
sb.Append(doc1.OuterXml);
sb.Append(doc2.OuterXml);

The just send sb.ToString() to the WebService.

Hope I haven't got completely the wrong end of the stick.

Works (somewhat)! Thanks, heres the code:

Stream requestStream;
Stream responseStream;
WebResponse response;
StreamReader sr;
byte[] postData;
string postString;
postString = xmlAccess.OuterXml + xmlRequest.OuterXml;
postData = Encoding.UTF8.GetBytes(postString);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://wwwcie.ups.com/ups.app/xml/Track");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
requestStream = request.GetRequestStream();

requestStream.Write(postData, 0, postData.Length);
requestStream.Close();

response = request.GetResponse();
responseStream = response.GetResponseStream();
sr = new StreamReader(responseStream);

return sr.ReadToEnd();

It still doesnt return proper XML though:

<?xml version="1.0" encoding="utf-8" ?> 
  <string xmlns="http://namespace/"><?xml version="1.0" ?> <TrackResponse><Response><...

Not sure why there's 2x <?xml version...

I'm doing this now with UPS, instead of building the documents in XML, I just used string builders like so:

... in code:

AddNode("name", "value");

...in class:

private StringBuilder sb;
public void AddNode(string name, string value) 
{
    sb.Append("<" + name + ">" + value + "</" + name + ">");
}

I personally think it's better, because it reduces the server load.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!