in my code,when XmlSchema just have namespace attr, i use JAXB tranlate object to xmlstring,i can get what i want. the xml string like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<FoodSchema xmlns="http://www.something.com/something">
<beverage>water</beverage>
<food>steak</food>
</FoodSchema>
but when I have xmlns attr ,i get xml like this:
<?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>
the code: 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);
}
}
what should i do , i can get
<?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>
Try using the annotations in package-info.java like this:
@javax.xml.bind.annotation.XmlSchema(namespace = "http://myOutput", xmlns = {@XmlNs(prefix = "", namespaceURI = "http://myOutput")}, elementFormDefault = XmlNsForm.QUALIFIED)
This way I got rid of the ns2 on the root element...