开发者

Converting XML document to URL encoded query string for HTTP POST - C#

I'm posting to a web page which I was told took XML as it's body. Turns out that what it really requires is what looks like a URL encoded CGI query string:

<FIRST>
  <ELEMENT1>Value1</ELEMENT1>
  <ELEMENT2>Value1</ELEMENT2>
  <ELEMENT3>Value1</ELEMENT3>
</FIRST>

<SECOND>
  <ELEMENT1>Value1</ELEMENT1>
  <ELEMENT2>Value1</ELEMENT2>
</SECOND>

Needs to be transmitted as

FIRST_ELEMENT1=VALUE1&FIRST_ELEMENT2=VALUE2&FIRST_ELEMENT3=VALUE3&SECOND_ELEMENT1=VALUE1&SECOND_ELEMENT2=VALUE2

The third party tells me this is a common usage, although I've not seen it before (as a method of submitting XML) it's obvious that the service was designed to take an HTML POST with a form as the source of data.

While I can see how I could write a transform I'm wondering if there is a mthod in the .Net framwork which achieves this translation. Upto and including .Net 3.5 is available on this project.开发者_JAVA技巧

Thanks in advance Dave


I've never seen that usage, but something like:

var query = string.Join("&",(
            from parent in XElement.Parse(xml).Elements()
            from child in parent.Elements()
            select HttpUtility.UrlEncode(parent.Name.LocalName) + "_"
                 + HttpUtility.UrlEncode(child.Name.LocalName) + "="
                 + HttpUtility.UrlEncode(child.Value)).ToArray());


I strongly doubt there's anything built-in to achieve this, but coding it up shouldn't be hard. I'd use a recursive method that examines the children of a node, calling itself with a string prefix that represents the position of the node in the tree. Maintain a List or a Dictionary or whatever best suits your needs outside of the method and when you encounter a node with text data, append the prefix+tag and the value to your list. Then it'll be trivial to go through that list and join them in the querystring format. Take care to escape ampersands and other reserved characters, though.


That seems pretty crazy, I hope your XML data isn't very long... you're likely to run into issues if the querystring ends up too long.

I don't understand why you can't do an HTTP-POST , set the content-type to 'text/xml', and simply post the raw XML data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜