gpt4 book ai didi

java - 从 JAXB 泛型中删除 xsi :type, xmlns :xs, 和 xmlns:xsi

转载 作者:搜寻专家 更新时间:2023-10-31 20:29:56 28 4
gpt4 key购买 nike

在使用 JAXB 时,我想在使用泛型时从我的 XML 元素中删除多余的命名空间/类型。我该怎么做或者我做错了什么?我想使用泛型,这样我只需编写一次代码块。

示例代码:

public static void main(String[] args) {
try {
TestRoot root = new TestRoot();
root.name.value = "bobby";
root.age.value = 102;
root.color.value = "blue";

JAXBContext context = JAXBContext.newInstance(root.getClass());
Marshaller marsh = context.createMarshaller();
marsh.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
marsh.marshal(root,pw);
System.out.println(sw.toString());
}
catch(Throwable t) {
t.printStackTrace();
}
}

@XmlRootElement
static class TestRoot {
@XmlElement public TestGeneric<String> name = new TestGeneric<String>(true);
@XmlElement public TestGeneric<Integer> age = new TestGeneric<Integer>(true);
@XmlElement public TestWhatIWouldLike color = new TestWhatIWouldLike(true);
}

@XmlAccessorType(XmlAccessType.NONE)
static class TestGeneric<T> {
@XmlAttribute public boolean isRequired;
@XmlElement public T value;

public TestGeneric() {
}

public TestGeneric(boolean isRequired) {
this.isRequired = isRequired;
}
}

@XmlAccessorType(XmlAccessType.NONE)
static class TestWhatIWouldLike {
@XmlAttribute public boolean isRequired;
@XmlElement public String value;

public TestWhatIWouldLike() {
}

public TestWhatIWouldLike(boolean isRequired) {
this.isRequired = isRequired;
}
}

输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testRoot>
<name isRequired="true">
<value xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">bobby</value>
</name>
<age isRequired="true">
<value xsi:type="xs:int" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">102</value>
</age>
<color isRequired="true">
<value>blue</value>
</color>
</testRoot>

最佳答案

我能够在属性上使用 @XmlAnyElement(lax=true) 由于泛型参数而导致我出现问题,然后不得不在正在编码的实际类上添加一个 @XmlRootElement,声明消失了!太棒了!

关于java - 从 JAXB 泛型中删除 xsi :type, xmlns :xs, 和 xmlns:xsi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11192623/

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