我正在尝试用 java 解析 Geocaching GPX 文件。这些 GPX 文件基于带有附加 XSD 文件的标准 GPX XSD 文件。
对于类生成,我使用 jaxb-maven-plugin。
除了 pom.xml:
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<packageName>de.darkspirit510.gpxparser</packageName>
</configuration>
</plugin>
</plugins>
XSD 文件:
我的问题:基本 XSD 定义了一个 any 属性来扩展另一个 XSD。使用以下代码片段解组我的 GPX 文件(使用所有相关类和 ObjectFactory)时:
Gpx gpx = (Gpx) JAXBContext
.newInstance(Gpx.class, Cache.class, ObjectFactory.class)
.createUnmarshaller()
.unmarshal(inputStream);
和一个 GPX 文件(除外)
<wpt lat="52.171967" lon="10.55625">
<time>2015-07-14T07:00:00Z</time>
<name>GC5ZA4J</name>
<desc>Bücherei WF-Nordost by OLEarius, Traditional Cache (1/1.5)</desc>
<url>http://www.geocaching.com/seek/cache_details.aspx?guid=4ac2a247-bd30-463a-96d7-3586abfebfcc</url>
<urlname>Bücherei WF-Nordost</urlname>
<sym>Geocache</sym>
<type>Geocache|Traditional Cache</type>
<groundspeak:cache id="5109967" available="True" archived="False" xmlns:groundspeak="http://www.groundspeak.com/cache/1/0">
<groundspeak:name>Bücherei WF-Nordost</groundspeak:name>
<groundspeak:placed_by>OLEarius</groundspeak:placed_by>
<groundspeak:owner id="6606006">OLEarius</groundspeak:owner>
<groundspeak:type>Traditional Cache</groundspeak:type>
<groundspeak:container>Other</groundspeak:container>
[...]
</groundspeak:cache>
</wpt>
使用这种组合,我可以创建一些 java 类并解析一个地理缓存 GPX 文件,其中包含在基本 XSD 中定义的所有字段。未编组的对象有一个 getAny() 方法,它返回只包含一个元素的 List。我的 IDE 告诉我该元素属于 ElementNSImpl 类,而不是 Cache。根据一些博客文章,GPX 类和 Cache 类的任何元素都需要特定的注释。但是 maven 插件已经生成了这些注释:
GPX类:
@XmlAnyElement(lax = true)
protected List<Object> any;
缓存类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "cache", namespace = "http://www.groundspeak.com/cache/1/0/1")
public class Cache {
ElementNSImpl 对象中的实际内容包含我的 GPX 文件的所有值。如何直接创建 Cache 类的对象?