1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.puppycrawl.tools.checkstyle.internal.utils;
21
22 import java.io.IOException;
23 import java.io.StringReader;
24 import java.util.LinkedHashSet;
25 import java.util.Set;
26
27 import javax.xml.parsers.DocumentBuilder;
28 import javax.xml.parsers.DocumentBuilderFactory;
29 import javax.xml.parsers.ParserConfigurationException;
30
31 import org.junit.Assert;
32 import org.w3c.dom.Document;
33 import org.w3c.dom.Node;
34 import org.xml.sax.InputSource;
35 import org.xml.sax.SAXException;
36
37 import com.puppycrawl.tools.checkstyle.XmlLoader;
38
39
40
41
42
43 public final class XmlUtil {
44
45 private XmlUtil() {
46 }
47
48 public static Document getRawXml(String fileName, String code, String unserializedSource)
49 throws ParserConfigurationException {
50 Document rawXml = null;
51 try {
52 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
53 factory.setValidating(false);
54 factory.setFeature(
55 XmlLoader.LoadExternalDtdFeatureProvider.EXTERNAL_GENERAL_ENTITIES, false);
56 factory.setFeature(
57 XmlLoader.LoadExternalDtdFeatureProvider.LOAD_EXTERNAL_DTD, false);
58
59 final DocumentBuilder builder = factory.newDocumentBuilder();
60
61 rawXml = builder.parse(new InputSource(new StringReader(code)));
62 }
63 catch (IOException | SAXException ex) {
64 Assert.fail(fileName + " has invalid xml (" + ex.getMessage() + "): "
65 + unserializedSource);
66 }
67
68 return rawXml;
69 }
70
71 public static Set<Node> getChildrenElements(Node node) {
72 final Set<Node> result = new LinkedHashSet<>();
73
74 for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
75 if (child.getNodeType() != Node.TEXT_NODE) {
76 result.add(child);
77 }
78 }
79
80 return result;
81 }
82
83 public static Node getFirstChildElement(Node node) {
84 Node firstChildElement = null;
85 for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
86 if (child.getNodeType() != Node.TEXT_NODE) {
87 firstChildElement = child;
88 break;
89 }
90 }
91
92 return firstChildElement;
93 }
94
95 public static Set<Node> findChildElementsByTag(Node node, String tag) {
96 final Set<Node> result = new LinkedHashSet<>();
97
98 for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
99 if (tag.equals(child.getNodeName())) {
100 result.add(child);
101 }
102 else if (child.hasChildNodes()) {
103 result.addAll(findChildElementsByTag(child, tag));
104 }
105 }
106
107 return result;
108 }
109
110 }