- public static void writeValueByType(final Element element, final TypeDefinition<?> type, final XmlCodecProvider codecProvider, final Object nodeValue) {
- TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
- if (baseType instanceof IdentityrefTypeDefinition) {
- if (nodeValue instanceof QName) {
- QName value = (QName) nodeValue;
- String prefix = "x";
- if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
- prefix = value.getPrefix();
- }
- element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
- element.setTextContent(prefix + ":" + value.getLocalName());
- } else {
- Object value = nodeValue;
- logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
- baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
- if (value != null) {
- element.setTextContent(String.valueOf(value));
- }
- }
- } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
- if (nodeValue instanceof InstanceIdentifier) {
- INSTANCE_IDENTIFIER_FOR_XML_CODEC.serialize((InstanceIdentifier)nodeValue,element);
- } else {
- Object value = nodeValue;
- logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
- .getNamespace(), //
- baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
- if (value != null) {
- element.setTextContent(String.valueOf(value));
- }
- }
- } else {
- if (nodeValue != null) {
- final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
- if (codec != null) {
- try {
- final String text = codec.serialize(nodeValue);
- element.setTextContent(text);
- } catch (ClassCastException e) {
- logger.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", nodeValue, baseType, e);
- element.setTextContent(String.valueOf(nodeValue));
- }
- } else {
- logger.error("Failed to find codec for {}, falling back to using stream", baseType);
- element.setTextContent(String.valueOf(nodeValue));