如何在Erlang中对一个字符串进行XML编码? [英] How do I XML-encode a string in Erlang?

查看:163
本文介绍了如何在Erlang中对一个字符串进行XML编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个erlang字符串,可能包含像& <等等:

  1> Unenc =string& \stuff \<
ok

是否有Erlang功能解析字符串并编码所有需要的HTML / XML实体的地方,例如:

  2> Enc = xmlencode(Unenc) 。
string& amp; amp; amp; &安培; QUOT;东西&安培; QUOT; & lt;。



我的用例是来自用户输入的相对较短的字符串,xmlencode函数的输出字符串将是XML属性的内容:

 code>< company name =Acme& amp; amp; amp; C.currency =& euro;/> 

最终的XML将被发送

解决方案

Erlang分发中有一个函数可以转义尖括号和&符号,但没有记录可能不是最好依靠它:

  1> xmerl_lib:export_text(string& \stuff \ ;)。
string& amp; amp; amp; \stuff \&

如果你想要构建/编码XML结构(而不​​仅仅是编码单个字符串),那么xmerl API将是一个很好的选择,例如

  2> xmerl :export_simple([{foo,[],[string& \stuff \<]}],xmerl_xml)
[<?xml version = \1.0\ ?>,
[[[,foo,>],
[string& amp; amp; \stuff \& lt;],
[
pre>

I have a erlang string which may contain characters like & " < and so on:

1> Unenc = "string & \"stuff\" <".
ok

Is there a Erlang function somewhere that parses the string and encodes all the needed HTML/XML entities, such as:

2> Enc = xmlencode(Unenc).
"string &amp; &quot;stuff&quot; &lt;".

?

My use case is for relatively short strings, which come from user input. The output strings of the xmlencode function will be the content of XML attributes:

<company name="Acme &amp; C." currency="&euro;" />

The final XML will be sent over the wire appropriately.

解决方案

There is a function in the Erlang distribution that escapes angle brackets and ampersands but it isn't documented so probably not best to rely on it:

1> xmerl_lib:export_text("string & \"stuff\" <").
"string &amp; \"stuff\" &lt;"

If you're wanting to build/encode XML structures (instead of just encoding a single string), then the xmerl API would be a good option, e.g.

2> xmerl:export_simple([{foo, [], ["string & \"stuff\" <"]}], xmerl_xml).
["<?xml version=\"1.0\"?>",
 [[["<","foo",">"],
   ["string &amp; \"stuff\" &lt;"],
   ["</","foo",">"]]]]

这篇关于如何在Erlang中对一个字符串进行XML编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆