JAXB如何在JDK7中删除ns2

时间:2014-08-04 14:43:01

标签: xml namespaces jaxb ns2

在我的代码中,当XmlSchema只有名称空间attr时, 我使用JAXB tranlate对象到xmlstring,我可以得到我想要的。 像这样的xml字符串:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<FoodSchema xmlns="http://www.something.com/something">
    <beverage>water</beverage>
    <food>steak</food>
</FoodSchema>

但是当我有xmlns attr时,我得到像这样的xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:FoodSchema xmlns:xsi="h" xmlns:ns2="http://www.something.com/something">
    <ns2:beverage>water</ns2:beverage>
    <ns2:food>steak</ns2:food>
</ns2:FoodSchema>

代码: package-info.java

    @XmlSchema(
        namespace="http://www.something.com/something", 
        elementFormDefault=XmlNsForm.QUALIFIED,
        xmlns = { @XmlNs(namespaceURI = "h", prefix = "xsi")})//only this make the result different


package com.test;

import javax.xml.bind.annotation.*;

Food.java

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Food {

    private String food;
    private String beverage;

    public String getFood() {
        return food;
    }

    public void setFood(String food) {
        this.food = food;
    }

    public String getBeverage() {
        return beverage;
    }

    public void setBeverage(String beverage) {
        this.beverage = beverage;
    }

}

Demo.java

package com.test;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jaxbContext = JAXBContext.newInstance(Food.class);

        Food foodSchema = new Food();
        foodSchema.setFood("steak");
        foodSchema.setBeverage("water");

        JAXBElement<Food> element = new JAXBElement<Food> (new QName("http://www.something.com/something","FoodSchema"), Food.class, foodSchema);

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(element, System.out);


    }
}

我应该怎么做,我可以得到

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <FoodSchema xmlns:xsi="h" xmlns="http://www.something.com/something">
        <beverage>water</beverage>
        <food>steak</food>
    </FoodSchema>

1 个答案:

答案 0 :(得分:5)

尝试使用package-info.java中的注释,如下所示:

@javax.xml.bind.annotation.XmlSchema(namespace = "http://myOutput", xmlns = {@XmlNs(prefix = "", namespaceURI = "http://myOutput")}, elementFormDefault = XmlNsForm.QUALIFIED)

这样我就摆脱了根元素上的ns2 ......