gpt4 book ai didi

java - jaxb 中两个不同但名称相同的元素

转载 作者:行者123 更新时间:2023-11-29 05:52:58 33 4
gpt4 key购买 nike

我正在尝试使用 JAXB解析以下 XML .我删除了不相关的部分。可惜原来XML由第三方应用程序生成,我没有 DTDXSD文件可用,所以我正在构建我的 JAXB手动编码。

<add>
<add-attr attr-name="UserName">
<value type="string">User1</value>
</add-attr>
<add-attr attr-name="Name">
<value type="structured">
<component name="familyName">Doe</component>
<component name="givenName">John</component>
</value>
</add-attr>
</add>

问题当然是<value>元素。这可以是纯文本元素,或者如果其属性类型是“结构化的 <component> 元素列表”。

我已经创建了两个类(value1 和 value2)来实现这两个选项,但我不知道 JAXB使用哪一个,因为元素都被命名为“值”。有什么解决办法吗?

最佳答案

选项 #1 - 一个值类

您可以有一个 Value 类,其中包含一个用 @XmlMixed 注释的 String 属性。

package forum13232991;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Value {

@XmlAttribute
String type;

@XmlMixed
List<String> value;

@XmlElement(name="component")
List<Component> components;

}

选项 #2 - 通过 XmlAdapter 的多个值类

如果您希望它们成为单独的类,您可以为此利用 XmlAdapter:

值适配器

package forum13232991;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class ValueAdapter extends XmlAdapter<Value, Object> {

@Override
public Value marshal(Object object) throws Exception {
Value value = new Value();
if(object instanceof StructuredValue) {
StructuredValue structuredValue = (StructuredValue) object;
value.type = "structured";
value.components = structuredValue.components;
} else {
StringValue stringValue = (StringValue) object;
value.value.add(stringValue.value);
}
return value;
}

@Override
public Object unmarshal(Value value) throws Exception {
if("string".equals(value.type)) {
StringValue stringValue = new StringValue();
StringBuilder strBldr = new StringBuilder();
for(String string : value.value) {
strBldr.append(string);
}
stringValue.value = strBldr.toString();
return stringValue;
} else {
StructuredValue structuredValue = new StructuredValue();
structuredValue.components = value.components;
return structuredValue;
}
}

}

AddAttr

package forum13232991;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

public class AddAttr {

@XmlJavaTypeAdapter(ValueAdapter.class)
Object value;

}

了解更多信息

关于java - jaxb 中两个不同但名称相同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13232991/

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