e151fca00969d9bc5e4e29fbe81bc04ca1173c7d
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / XmlDocumentUtils.java
1 package org.opendaylight.controller.sal.connect.netconf;
2
3 import java.net.URI;
4 import java.util.ArrayList;
5 import java.util.List;
6
7 import org.opendaylight.yangtools.yang.common.QName;
8 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
9 import org.opendaylight.yangtools.yang.data.api.Node;
10 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
11 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
12 import org.w3c.dom.Document;
13 import org.w3c.dom.Element;
14 import org.w3c.dom.NodeList;
15
16 import com.google.common.base.Strings;
17
18 public class XmlDocumentUtils {
19
20     public static Node<?> toNode(Document doc) {
21         return toCompositeNode(doc.getDocumentElement());
22     }
23
24     private static Node<?> toCompositeNode(Element element) {
25         String orgNamespace = element.getNamespaceURI();
26         URI biNamespace = null;
27         if (orgNamespace != null) {
28             biNamespace = URI.create(orgNamespace);
29         }
30         QName qname = new QName(biNamespace, element.getLocalName());
31
32         List<Node<?>> values = new ArrayList<>();
33         NodeList nodes = element.getChildNodes();
34         boolean isSimpleObject = true;
35         String value = null;
36         for (int i = 0; i < nodes.getLength(); i++) {
37             org.w3c.dom.Node child = nodes.item(i);
38             if (child instanceof Element) {
39                 isSimpleObject = false;
40                 values.add(toCompositeNode((Element) child));
41             }
42             if (isSimpleObject && child instanceof org.w3c.dom.Text) {
43                 value = element.getTextContent();
44                 if (!Strings.isNullOrEmpty(value)) {
45                     isSimpleObject = true;
46                 }
47             }
48         }
49
50         if (isSimpleObject) {
51             return new SimpleNodeTOImpl<>(qname, null, value);
52         }
53         return new CompositeNodeTOImpl(qname, null, values);
54     }
55 }