简体   繁体   中英

Generate valid XML name in Java

Are there any helpers that will transform/escape a string to be a valid XML name ?

Example, I have the string max(OfAll) and need to generate some XML like eg

<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 ?

(For comparison, .NET have some methods that the above xml fragment would be:

 <max_x028_OfAll_x028_>SomeText</<max_x028_OfAll_x028_>)

The encoding in your .NET example looks like the one defined in 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. 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. It can escape text for use in XML documents, I'm not aware of anything to escape XML element names.

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

我不知道有什么辅助方法,但是这里的规则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.

For the record, what you are doing is frequently called "name mangling".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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