1

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.

Thanks in advance Dave

3 Answers 3

3

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Neat solution Marc. The third party is adamant that this is 'streamed XML' - fantasy datatype I think. Still this helps achive the desired output. Many thanks.
1

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.

Comments

0

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.

1 Comment

Believe me I tried that. The post succeeds but the application at the other end does not parse XML, it expects the query string. Looks like a home rolled system, I know there is a mainframe sitting on the back end, perhaps it's not XML enabled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.