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 String IDX_ATTRIBUTE = "idx";
16

    
17
	public static ValueMap parseNodeList(final NodeList nodeList) {
18
		final ValueMap values = new ValueMap();
19

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

    
26
	protected static void getNodeValue(final Node node, final ValueMap values) {
27

    
28
		final String nodeName = node.getLocalName().toLowerCase();
29

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

    
34
		final NamedNodeMap attributeList = node.getAttributes();
35
		for (int j = 0; j < attributeList.getLength(); j++) {
36
			Node attr = attributeList.item(j);
37
			if ((attr.getNodeValue() != null) && !attr.getNodeValue().isEmpty()) {
38
				attrs.put(attr.getLocalName(), attr.getNodeValue());
39
				if (values.containsKey(nodeName)) {
40
					attrs.put(IDX_ATTRIBUTE, String.valueOf(values.get(nodeName).size() + 1));
41
				} else {
42
					attrs.put(IDX_ATTRIBUTE, "1");
43
				}
44
			}
45
		}
46
		element.setAttributes(attrs);
47

    
48
		if (!element.isEmpty()) {
49
			if (!values.containsKey(nodeName)) {
50
				values.put(nodeName, new ElementList());
51
			}
52

    
53
			values.get(nodeName).add(element);
54
		}
55
	}
56

    
57
	@Override
58
	public ElementList get(final Object key) {
59
		ElementList e = super.get(key);
60
		return e != null ? e : new ElementList();
61
	}
62

    
63
	@Override
64
	public String toString() {
65
		StringBuilder sb = new StringBuilder();
66
		sb.append("{");
67
		for (String k : this.keySet()) {
68
			sb.append(k).append("=").append(this.get(k)).append("\n");
69
		}
70
		sb.append("}");
71
		return sb.toString();
72
	}
73
}
(10-10/10)