如何在Erlang中对一个字符串进行XML编码? [英] How do I XML-encode a string in 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)
pre>
[<?xml version = \1.0\ ?>,
[[[,foo,>],
[string& amp; amp; \stuff \& lt;],
[,foo,>]]]]
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 & "stuff" <".
?
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 & C." currency="€" />
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 & \"stuff\" <"
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 & \"stuff\" <"], ["</","foo",">"]]]]
这篇关于如何在Erlang中对一个字符串进行XML编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!