简体   繁体   English

将JAXB注释与值一起使用

[英]Use JAXB Annotation With Value

When generating XML using JAXB annotations, I know it's not possible to use @XmlElement(name="City") & @XmlValue on the same Java member because they are mutually exclusive. 当使用JAXB注释生成XML时,我知道无法在同一Java成员上使用@XmlElement(name="City")@XmlValue ,因为它们是互斥的。 Is it possible to @XmlElement to produce an XML tag with a value at the same time? @XmlElement是否可以同时生成带有值的XML标签? Not being able to do this causes a ton of objects to be created and seems to be overkill. 无法执行此操作将导致创建大量对象,这似乎是过大的。

Java Code Java代码

....
@XmlElement(name="City")
@XmlValue       <---- I'm wanting to do this but I'm limited by the API
private String city;

Expected Output 预期产量

....
<City>some value here</City>
....

We can try to achieve the same using another type which uses @XmlValue annotation. 我们可以尝试使用另一种使用@XmlValue批注的类型来实现相同的@XmlValue

Below is what you can try - 以下是您可以尝试的-

@XmlRootElement(name="CityRoot")
@XmlType(name="CityRootType")
public class CityRoot {
    @XmlElement(name="City")
    public CityName s;
}

CityName definition as below CityName定义如下

public class CityName {
    @XmlValue
    String name;
}

Now, feed these two files to schemagen to have the .xsd file generated and using that generate .xml file to verify. 现在,将这两个文件提供给schemagen以生成.xsd文件,并使用该生成的.xml文件进行验证。

Below is how generated xml file looks like when I generated it - 以下是生成XML文件时的样子-

<?xml version="1.0" encoding="UTF-8"?>
<CityRoot>
      <City>SomeCityName</City>
</CityRoot>

If you want to have an element with simple text, the only annotation you need is the @XmlElement annotation. 如果要使用简单文本元素,则唯一需要的注释就是@XmlElement注释。 If the type of a field is String, JAXB generates an xml element with the value of the String as the value of the element. 如果字段的类型为String,则JAXB会生成一个XML元素,其中String的值为该元素的值。

The only thing you need is this: 您唯一需要的是:

@XmlElement(name="City")
private String city;

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

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