Java:编组对象—在xml中删除额外的ns2注释

我试图将对象内的数据编组为基于已定义架构的xml文件。但是,当我打印出xml文件时,我会在xml标签上收到额外的注释。有什么办法摆脱多余的命名空间注释(即ns2)

这是我从编组中收到的xml的示例。

<?xml version="1.0" encoding="UTF-8" standalone="yes">

<root xmlns:ns2="http://www.something.com/something">

<ns2:food>steak</ns2:food>

<ns2:beverage>water</ns2:beverage>

</root>

我想要的是这样的:

<?xml version="1.0" encoding="UTF-8" standalone="yes">

<root xmlns="http://www.something.com/something">

<food>steak</food>

<beverage>water</beverage>

</root>

这是我的Java代码正在做的事情:

            JAXBContext context = JAXBContext.newInstance("com.schema");

JAXBElement<FoodSchema> element = new JAXBElement<FoodSchema>

(new QName("FoodSchema"), Food.class, foodSchema);

Marshaller marshaller = context.createMarshaller();

OutputStream os = new FileOutputStream(object.getFilePath());

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

marshaller.marshal(element, os);

任何帮助深表感谢!谢谢!

回答:

通过向QName用于构造JAXB元素的名称空间添加URI名称空间URI(“

http://www.something.com/something”),并利用包级@XmlSchema注释,将为您提供所需的名称空间限定:

@XmlSchema(

namespace="http://www.something.com/something",

elementFormDefault=XmlNsForm.QUALIFIED)

package forum7014746;

import javax.xml.bind.annotation.*;

package forum7014746;

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;

}

}

package forum7014746;

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="http://www.something.com/something">

<beverage>water</beverage>

<food>steak</food>

</FoodSchema>

以上是 Java:编组对象—在xml中删除额外的ns2注释 的全部内容, 来源链接: utcz.com/qa/424486.html

回到顶部