简体   繁体   中英

Jaxb Unmarshalling java files from XML file with namespace

This is my XML

<?xml version="1.0"?>
<gpx version="1.1" creator="Example" xmlns="http://www.Example.com/1" xmlns:football="https://www.Example-football.com/xsd/football-ext">
    <metadata>
        <name>hello world</name>
        <time>2018-04-26T12:32:52</time>
        <extensions>
            <sportsMeta>
                <football:length>5080.3714454417996</football:length>
            </sportsMeta>
        </extensions>
    </metadata>
</gpx>

Added this to package-info.java

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.Example.com/1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, attributeFormDefault = XmlNsForm.UNQUALIFIED, xmlns = {
        @javax.xml.bind.annotation.XmlNs(prefix = "football", namespaceURI = "https://www.Example-football.com/xsd/football-ext"),
        @javax.xml.bind.annotation.XmlNs(prefix = "", namespaceURI = "https://www.Example-football.com/xsd/football-ext/1/1") })
package com.example.football.share.gpx;

import javax.xml.bind.annotation.XmlNsForm;

I am able to read name, time. But not able to read guid, length.

Here is SportsMeta.java

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportsMeta", propOrder = {
        "length"
})
public class SportsMeta {

    protected BigDecimal length;

    public BigDecimal getLength() {
        return length;
    }

    public void setLength(BigDecimal length) {
        this.length = length;
    }
}

How can I read length info from the XML file.

In your XML input you have this part:

<sportsMeta>
    <football:length>5080.3714454417996</football:length>
</sportsMeta>

where the namespace prefix football refers to the namespace URI
"https://www.Example-football.com/xsd/football-ext" as defined by xmlns:football="https://www.Example-football.com/xsd/football-ext" in your XML.

To map this XML to Java correctly you need to specify that namespace URI for the length property of your SportsMeta class. You do this by annotating the length property with @XmlElement and specifying the namespace within there. (See also the API documentation of XmlElement.namespace .)

@XmlElement(namespace = "https://www.Example-football.com/xsd/football-ext")
protected BigDecimal length;

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