Project

General

Profile

1
package eu.dnetlib.data.transform.xml;
2

    
3
import java.util.HashMap;
4
import java.util.Map;
5

    
6
import org.w3c.dom.NamedNodeMap;
7
import org.w3c.dom.Node;
8
import org.w3c.dom.NodeList;
9

    
10
import com.google.common.collect.Maps;
11

    
12
@SuppressWarnings("serial")
13
public class ValueMap extends HashMap<String, ElementList> {
14

    
15
	public static ValueMap parseNodeList(final NodeList nodeList) {
16
		final ValueMap values = new ValueMap();
17

    
18
		for (int i = 0; i < nodeList.getLength(); i++) {
19
			getNodeValue(nodeList.item(i), values);
20
		}
21
		return values;
22
	}
23

    
24
	protected static void getNodeValue(final Node node, final ValueMap values) {
25

    
26
		final String nodeName = node.getLocalName().toLowerCase();
27

    
28
		final Node nodeText = node.getFirstChild();
29
		final Element element = nodeText != null ? new Element(nodeText.getNodeValue()) : new Element();
30
		final Map<String, String> attrs = Maps.newHashMap();
31

    
32
		final NamedNodeMap attributeList = node.getAttributes();
33
		for (int j = 0; j < attributeList.getLength(); j++) {
34
			Node attr = attributeList.item(j);
35
			if ((attr.getNodeValue() != null) && !attr.getNodeValue().isEmpty()) {
36
				attrs.put(attr.getLocalName(), attr.getNodeValue());
37
			}
38
		}
39
		element.setAttributes(attrs);
40

    
41
		if (!element.isEmpty()) {
42
			if (!values.containsKey(nodeName)) {
43
				values.put(nodeName, new ElementList());
44
			}
45

    
46
			values.get(nodeName).add(element);
47
		}
48
	}
49

    
50
	@Override
51
	public ElementList get(final Object key) {
52
		ElementList e = super.get(key);
53
		return e != null ? e : new ElementList();
54
	}
55

    
56
	@Override
57
	public String toString() {
58
		StringBuilder sb = new StringBuilder();
59
		sb.append("{");
60
		for (String k : this.keySet()) {
61
			sb.append(k).append("=").append(this.get(k)).append("\n");
62
		}
63
		sb.append("}");
64
		return sb.toString();
65
	}
66
}
(10-10/10)