简体   繁体   English

用Java生成有效的XML名称

[英]Generate valid XML name in Java

Are there any helpers that will transform/escape a string to be a valid XML name ? 是否有任何帮助程序会将字符串转换/转义为有效的XML名称?

Example, I have the string max(OfAll) and need to generate some XML like eg 例如,我有字符串max(OfAll) ,需要生成一些XML,例如

<max(OfAll)>SomeText</<max(OfAll)>

That's obviously not a valid name, are there some helper methods that can transform the string to be a valid xml name ? 显然这不是一个有效的名称,是否有一些辅助方法可以将字符串转换为有效的xml名称?

(For comparison, .NET have some methods that the above xml fragment would be: (为了进行比较,.NET有一些上面的xml片段将是的方法:

 <max_x028_OfAll_x028_>SomeText</<max_x028_OfAll_x028_>)

The encoding in your .NET example looks like the one defined in ISO9075. .NET示例中的编码类似于ISO9075中定义的编码。 I don't think there is a built-in implementation in the jdk, but this encoding is also used by content repositories like alfresco or jackrabbit for their xml import/exports and query apis. 我认为jdk中没有内置的实现,但是这种编码也被alfresco或jackrabbit之类的内容存储库用于其XML导入/导出和查询api。 A quick search turned up these two implementations, both available under open source licenses: 快速搜索发现了这两种实现,它们都可以在开源许可下使用:

One class which may be of use in other situations is StringEscapeUtils in the apache commons-lang project. apache commons-lang项目中的StringEscapeUtils是可能在其他情况下使用的一类。 It can escape text for use in XML documents, I'm not aware of anything to escape XML element names. 它可以转义要在XML文档中使用的文本,我不知道要转义XML元素名称的任何内容。

Could you not generate something more readable such as 您能否生成更易读的内容,例如

<aggregation type="max(OfAll)">SomeText</aggregation>

There are lots of libraries available to marshall/unmarshall objects to xml and back including JAXB (part of the JDK), JiBX , Castor , XStream 有很多库可用于将对象编组/解组到xml以及返回到xml,包括JAXB (JDK的一部分), JiBXCastorXStream

我不知道有什么辅助方法,但是这里的规则http://www.w3.org/TR/REC-xml/#NT-Name非常简单,因此应该很容易实现。

As should be clear, normal XML escaping (replacing inappropriate characters with character entities) does not result in a valid XML identifier. 应当清楚,正常的XML转义(用字符实体替换不适当的字符)不会产生有效的XML标识符。

For the record, what you are doing is frequently called "name mangling". 根据记录,您所做的通常称为“名称修改”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM