Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse XML with Opa?

if you want to connect an Opa web client with a XML-RPC server. The right way to send a request is probably

xml request_body = @xml(
  <methodCall>
    <methodName>my_rpc_method</methodName>
    <params>some_rpc_params</params>
  </methodCall>
)

request = WebClient.Post.of_xml(
  {WebClient.Post.default_options with
    content: {some: request_body}
  }
)

WebClient.Post.try_post_with_options_async(
  server_uri,
  request,
  callback
)

function callback(response) {
  ...
}

Now, what is the right way to parse the server response back into an Opa XML data structure? I have currently created my own XML parser for that, but this is certainly not the best practice.

The API shows several XML parsing functions like:

  • Xml_parser.try_parse
  • XmlConvert.of_string
  • Xmlns.try_parse (btw. what is the difference between the Xml and Xmlns data type in Opa?)
  • ...

but which of those would be the right one? The documentation doesn't (yet) tell much about their usage. Or might it be right to convert the server response directly in XML form via WebClient.Result.as_xml?

I created a repository that contains runnable code with the given problem. Feel free to fork and fix it.

What would be the best (and easiest) way to parse such a XML server response into a corresponding data structure?

JHannes

like image 629
JHannes Avatar asked Nov 17 '25 03:11

JHannes


1 Answers

Ok, so here's what the three functions that you mention do:

  • Xml_parser.try_parse is a function that invokes an XML parser. XML parsers are built using xml_parser keyword and are somewhat similar to Opa's parsers, except that they parse XML, not text.
  • XmlConvert.of_string is a function that converts a string to xml, so it's a trivial function that just builds XML consisting of a text node.
  • Xmlns.try_parse attempts an opposite conversion: i.e. it takes a string and tries to parse it into an `xml'.

So if you get a string response and want to process it then you'd usually:

  1. parse it into xml using Xmlns.try_parse
  2. built an xml_parser
  3. invoke it with Xml_parser.try_parse to get a structural representation of your XML data.

If you get your data as XML immediately then you can skip the first step above. Let me know if that helps.

like image 59
akoprowski Avatar answered Nov 19 '25 21:11

akoprowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!