gpt4 book ai didi

xml - JAXB 如何删除 JDK7 中的 ns2

转载 作者:数据小太阳 更新时间:2023-10-29 02:56:57 26 4
gpt4 key购买 nike

在我的代码中,当 XmlSchema 只有命名空间属性时,我使用 JAXB 将对象转换为 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>

代码:包信息.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.*;

食物.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;
}

}

演示.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>

最佳答案

尝试像这样使用 package-info.java 中的注释:

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

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

关于xml - JAXB 如何删除 JDK7 中的 ns2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25121333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com