ModifAction enum added NONE operation + additional checks
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlDocumentUtils.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import java.net.URI;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Random;
19 import java.util.Set;
20
21 import javax.activation.UnsupportedDataTypeException;
22 import javax.xml.parsers.DocumentBuilder;
23 import javax.xml.parsers.DocumentBuilderFactory;
24 import javax.xml.parsers.ParserConfigurationException;
25
26 import com.google.common.collect.Maps;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.data.api.*;
29 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
30 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.Node;
33 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
34 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
35 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
36 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
37 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
38 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
39 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
41 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.w3c.dom.*;
53
54 import com.google.common.base.Function;
55 import com.google.common.base.Objects;
56 import com.google.common.base.Optional;
57 import com.google.common.base.Preconditions;
58 import com.google.common.base.Strings;
59 import com.google.common.collect.ImmutableList;
60
61 public class XmlDocumentUtils {
62
63     private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
64
65         @Override
66         public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
67             return TypeDefinitionAwareCodec.from(baseType);
68         }
69     };
70
71     private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
72
73     /**
74      * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
75      * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
76      * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
77      * Node Container Schema and transformed accordingly.
78      *
79      * @param data Data DOM root element
80      * @param schema Data Node Container Schema
81      * @param codecProvider XML Codec Provider
82      * @return new instance of XML Document
83      * @throws UnsupportedDataTypeException
84      */
85     public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
86             throws UnsupportedDataTypeException {
87         Preconditions.checkNotNull(data);
88         Preconditions.checkNotNull(schema);
89
90         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
91         dbf.setNamespaceAware(true);
92         Document doc = null;
93         try {
94             DocumentBuilder bob = dbf.newDocumentBuilder();
95             doc = bob.newDocument();
96         } catch (ParserConfigurationException e) {
97             return null;
98         }
99
100         if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
101             doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
102             return doc;
103         } else {
104             throw new UnsupportedDataTypeException(
105                     "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
106         }
107     }
108
109     /**
110      * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
111      * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
112      * nodes of Data Tree are transformed accordingly.
113      *
114      * @param data Data DOM root element
115      * @param codecProvider XML Codec Provider
116      * @return new instance of XML Document
117      * @throws UnsupportedDataTypeException
118      */
119     public static Document toDocument(CompositeNode data, XmlCodecProvider codecProvider)
120             throws UnsupportedDataTypeException {
121         Preconditions.checkNotNull(data);
122
123         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
124         dbf.setNamespaceAware(true);
125         Document doc = null;
126         try {
127             DocumentBuilder bob = dbf.newDocumentBuilder();
128             doc = bob.newDocument();
129         } catch (ParserConfigurationException e) {
130             return null;
131         }
132
133         doc.appendChild(createXmlRootElement(doc, data, null, codecProvider));
134         return doc;
135     }
136
137     private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
138             XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
139         Element itemEl = createElementFor(doc, data);
140         if (data instanceof SimpleNode<?>) {
141             if (schema instanceof LeafListSchemaNode) {
142                 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
143                         (DataSchemaNode) schema, codecProvider);
144             } else if (schema instanceof LeafSchemaNode) {
145                 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
146                         (DataSchemaNode) schema, codecProvider);
147             } else {
148                 Object value = data.getValue();
149                 if (value != null) {
150                     itemEl.setTextContent(String.valueOf(value));
151                 }
152             }
153         } else { // CompositeNode
154             for (Node<?> child : ((CompositeNode) data).getChildren()) {
155                 DataSchemaNode childSchema = null;
156                 if (schema != null) {
157                     childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
158                     if (logger.isDebugEnabled()) {
159                         if (childSchema == null) {
160                             logger.debug("Probably the data node \""
161                                     + ((child == null) ? "" : child.getNodeType().getLocalName())
162                                     + "\" is not conform to schema");
163                         }
164                     }
165                 }
166                 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
167             }
168         }
169         return itemEl;
170     }
171
172     private static Element createElementFor(Document doc, Node<?> data) {
173         QName dataType = data.getNodeType();
174         Element ret;
175         if (dataType.getNamespace() != null) {
176             ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
177         } else {
178             ret = doc.createElementNS(null, dataType.getLocalName());
179         }
180         if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
181             for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
182                 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
183                         attribute.getValue());
184             }
185
186         }
187         return ret;
188     }
189
190     public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
191             DataSchemaNode schema, XmlCodecProvider codecProvider) {
192         TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
193
194         if (baseType instanceof IdentityrefTypeDefinition) {
195             if (node.getValue() instanceof QName) {
196                 QName value = (QName) node.getValue();
197                 String prefix = "x";
198                 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
199                     prefix = value.getPrefix();
200                 }
201                 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
202                 element.setTextContent(prefix + ":" + value.getLocalName());
203             } else {
204                 Object value = node.getValue();
205                 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
206                         baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
207                 if (value != null) {
208                     element.setTextContent(String.valueOf(value));
209                 }
210             }
211         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
212             if (node.getValue() instanceof InstanceIdentifier) {
213                 // Map< key = namespace, value = prefix>
214                 Map<String, String> prefixes = new HashMap<>();
215                 InstanceIdentifier instanceIdentifier = (InstanceIdentifier) node.getValue();
216                 StringBuilder textContent = new StringBuilder();
217                 for (PathArgument pathArgument : instanceIdentifier.getPath()) {
218                     textContent.append("/");
219                     writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
220                     if (pathArgument instanceof NodeIdentifierWithPredicates) {
221                         Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
222
223                         for (QName keyValue : predicates.keySet()) {
224                             String predicateValue = String.valueOf(predicates.get(keyValue));
225                             textContent.append("[");
226                             writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
227                             textContent.append("='");
228                             textContent.append(predicateValue);
229                             textContent.append("'");
230                             textContent.append("]");
231                         }
232                     } else if (pathArgument instanceof NodeWithValue) {
233                         textContent.append("[.='");
234                         textContent.append(((NodeWithValue)pathArgument).getValue());
235                         textContent.append("'");
236                         textContent.append("]");
237                     }
238                 }
239                 element.setTextContent(textContent.toString());
240
241             } else {
242                 Object value = node.getValue();
243                 logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
244                         .getNamespace(), //
245                         baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
246                 if (value != null) {
247                     element.setTextContent(String.valueOf(value));
248                 }
249             }
250         } else {
251             if (node.getValue() != null) {
252                 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
253                 if (codec != null) {
254                     try {
255                         final String text = codec.serialize(node.getValue());
256                         element.setTextContent(text);
257                     } catch (ClassCastException e) {
258                         logger.error("Provided node {} did not have type {} required by mapping. Using stream instead.", node, baseType, e);
259                         element.setTextContent(String.valueOf(node.getValue()));
260                     }
261                 } else {
262                     logger.error("Failed to find codec for {}, falling back to using stream", baseType);
263                     element.setTextContent(String.valueOf(node.getValue()));
264                 }
265             }
266         }
267     }
268
269     private static void writeIdentifierWithNamespacePrefix(Element element, StringBuilder textContent, QName qName,
270             Map<String, String> prefixes) {
271         String namespace = qName.getNamespace().toString();
272         String prefix = prefixes.get(namespace);
273         if (prefix == null) {
274             prefix = qName.getPrefix();
275             if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
276                 prefix = generateNewPrefix(prefixes.values());
277             }
278         }
279
280         element.setAttribute("xmlns:" + prefix, namespace.toString());
281         textContent.append(prefix);
282         prefixes.put(namespace, prefix);
283
284         textContent.append(":");
285         textContent.append(qName.getLocalName());
286     }
287
288     private static String generateNewPrefix(Collection<String> prefixes) {
289         StringBuilder result = null;
290         Random random = new Random();
291         do {
292             result = new StringBuilder();
293             for (int i = 0; i < 4; i++) {
294                 int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
295                 result.append(Character.toChars(randomNumber));
296             }
297         } while (prefixes.contains(result.toString()));
298
299         return result.toString();
300     }
301
302     public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
303         TypeDefinition<?> superType = type;
304         while (superType.getBaseType() != null) {
305             superType = superType.getBaseType();
306         }
307         return superType;
308     }
309
310     private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
311         if (dataSchemaNode != null && node != null) {
312             for (DataSchemaNode dsn : dataSchemaNode) {
313                 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
314                     return dsn;
315                 } else if (dsn instanceof ChoiceNode) {
316                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
317                         DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
318                         if (foundDsn != null) {
319                             return foundDsn;
320                         }
321                     }
322                 }
323             }
324         }
325         return null;
326     }
327
328     public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
329             Optional<XmlCodecProvider> codecProvider) {
330         if (schema.isPresent()) {
331             return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
332         }
333         return toDomNode(xmlElement);
334     }
335
336     public static CompositeNode fromElement(Element xmlElement) {
337         CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
338         node.setQName(qNameFromElement(xmlElement));
339
340         return node.toInstance();
341     }
342
343     private static QName qNameFromElement(Element xmlElement) {
344         String namespace = xmlElement.getNamespaceURI();
345         String localName = xmlElement.getLocalName();
346         return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
347     }
348
349     private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
350         checkQName(xmlElement, schema.getQName());
351         if (schema instanceof DataNodeContainer) {
352             return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
353         } else if (schema instanceof LeafSchemaNode) {
354             return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
355         } else if (schema instanceof LeafListSchemaNode) {
356             return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
357
358         }
359         return null;
360     }
361
362     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
363             XmlCodecProvider codecProvider) {
364         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
365         String text = xmlElement.getTextContent();
366         Object value;
367         if (codec != null) {
368             value = codec.deserialize(text);
369
370         } else {
371             value = xmlElement.getTextContent();
372         }
373
374         Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
375         return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
376     }
377
378     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
379             XmlCodecProvider codecProvider) {
380         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
381         String text = xmlElement.getTextContent();
382         Object value;
383         if (codec != null) {
384             value = codec.deserialize(text);
385
386         } else {
387             value = xmlElement.getTextContent();
388         }
389
390         Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
391         return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
392     }
393
394     private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
395             XmlCodecProvider codecProvider) {
396         List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
397         Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
398         return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
399     }
400
401     public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
402
403     public static Optional<ModifyAction> getModifyOperationFromAttributes(Element xmlElement) {
404         Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
405         if(attributeNodeNS == null)
406             return Optional.absent();
407
408         ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
409         Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
410
411         return Optional.of(action);
412     }
413
414     private static void checkQName(Element xmlElement, QName qName) {
415         checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
416         checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
417     }
418
419     private static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
420         if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
421             for (DataSchemaNode dsn : dataSchemaNode) {
422                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
423                     return Optional.<DataSchemaNode> of(dsn);
424                 } else if (dsn instanceof ChoiceNode) {
425                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
426                         Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
427                         if (foundDsn != null && foundDsn.isPresent()) {
428                             return foundDsn;
429                         }
430                     }
431                 }
432             }
433         }
434         return Optional.absent();
435     }
436
437     public static Node<?> toDomNode(Document doc) {
438         return toDomNode(doc.getDocumentElement());
439     }
440
441     private static Node<?> toDomNode(Element element) {
442         QName qname = qNameFromElement(element);
443
444         ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
445         NodeList nodes = element.getChildNodes();
446         boolean isSimpleObject = true;
447         String value = null;
448         for (int i = 0; i < nodes.getLength(); i++) {
449             org.w3c.dom.Node child = nodes.item(i);
450             if (child instanceof Element) {
451                 isSimpleObject = false;
452                 values.add(toDomNode((Element) child));
453             }
454             if (isSimpleObject && child instanceof org.w3c.dom.Text) {
455                 value = element.getTextContent();
456                 if (!Strings.isNullOrEmpty(value)) {
457                     isSimpleObject = true;
458                 }
459             }
460         }
461         if (isSimpleObject) {
462             return new SimpleNodeTOImpl<>(qname, null, value);
463         }
464         return ImmutableCompositeNode.create(qname, values.build());
465     }
466
467     public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
468         return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
469
470             @Override
471             public Optional<Node<?>> apply(Element input) {
472                 if (context.isPresent()) {
473                     QName partialQName = qNameFromElement(input);
474                     Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
475                     if (schemaNode.isPresent()) {
476                         return Optional.<Node<?>> fromNullable(//
477                                 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
478                     }
479                 }
480                 return Optional.<Node<?>> fromNullable(toDomNode(input));
481             }
482
483         });
484
485     }
486
487     /**
488      * Converts XML Document containing notification data from Netconf device to
489      * Data DOM Nodes. <br>
490      * By specification defined in <a
491      * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
492      * there are xml elements containing notifications metadata, like eventTime
493      * or root notification element which specifies namespace for which is
494      * notification defined in yang model. Those elements MUST be stripped off
495      * notifications body. This method returns pure notification body which
496      * begins in element which is equal to notifications name defined in
497      * corresponding yang model. Rest of notification metadata are obfuscated,
498      * thus Data DOM contains only pure notification body.
499      *
500      * @param document
501      *            XML Document containing notification body
502      * @param notifications
503      *            Notifications Definition Schema
504      * @return Data DOM Nodes containing xml notification body definition or
505      *         <code>null</code> if there is no NotificationDefinition with
506      *         Element with equal notification QName defined in XML Document.
507      */
508     public static CompositeNode notificationToDomNodes(final Document document,
509             final Optional<Set<NotificationDefinition>> notifications) {
510         if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
511             final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
512
513             for (int i = 0; i < originChildNodes.getLength(); i++) {
514                 org.w3c.dom.Node child = originChildNodes.item(i);
515                 if (child instanceof Element) {
516                     final Element childElement = (Element) child;
517                     final QName partialQName = qNameFromElement(childElement);
518                     final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
519                             notifications.get());
520                     if (notificationDef.isPresent()) {
521                         final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
522                         final List<Node<?>> domNodes = toDomNodes(childElement,
523                                 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes));
524                         return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
525                     }
526                 }
527             }
528         }
529         return null;
530     }
531
532     private static Optional<NotificationDefinition> findNotification(final QName notifName,
533             final Set<NotificationDefinition> notifications) {
534         if ((notifName != null) && (notifications != null)) {
535             for (final NotificationDefinition notification : notifications) {
536                 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
537                     return Optional.<NotificationDefinition>fromNullable(notification);
538                 }
539             }
540         }
541         return Optional.<NotificationDefinition>absent();
542     }
543
544     private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
545         ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
546         for (int i = 0; i < nodes.getLength(); i++) {
547             org.w3c.dom.Node child = nodes.item(i);
548             if (child instanceof Element) {
549                 Optional<T> result = forBody.apply((Element) child);
550                 if (result.isPresent()) {
551                     ret.add(result.get());
552                 }
553             }
554         }
555         return ret.build();
556     }
557
558     public static final XmlCodecProvider defaultValueCodecProvider() {
559         return DEFAULT_XML_VALUE_CODEC_PROVIDER;
560     }
561
562 }