简体   繁体   中英

How to use non-standard variable names in Java for producing XML tags?

I am trying to write the AndroidManifest.xml file programmatically through Java using Jaxb. The problem comes while defining the attributes, which follow a string:string naming convention. For example, the manifest element is defined thus:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="string"
          android:sharedUserId="string"
          android:sharedUserLabel="string resource" 
          android:versionCode="integer"
          android:versionName="string"
          android:installLocation=["auto" | "internalOnly" | "preferExternal"] >
    . . .
</manifest>

While doing this from Java, I cannot annotate the attributes because xmlns:android etc are not valid Java variables.

What is the best way to overcome this, while still using Jaxb, and not resorting to StringBuilder technique for generating the XML?

Here is an example from the javadoc of javax.xml.bind.annotation.XmlElement:

  @XmlElement(name="item-price")
  public java.math.BigDecimal price;

The name parameter is what you'll see in the XML.

But this android: the namespace prefix and should appear according to the namespace definition, which is the parameter of namespace:

  @XmlElement(name="item-price", namespace="http://schemas.android.com/apk/res/android")
  public java.math.BigDecimal price;

After marshalling, you'll most likely see "ns1:" in place of android:, but that's OK.

Easiest way to get the annotated Java code: Write (or find) the XML schema and run it through xjc . Works all the time - almost ;-)

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