71 lines
2.5 KiB
Java
71 lines
2.5 KiB
Java
package com.github.dtschust.zork.parser;
|
|
|
|
import org.w3c.dom.CharacterData;
|
|
import org.w3c.dom.Element;
|
|
import org.w3c.dom.Node;
|
|
import org.w3c.dom.NodeList;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Optional;
|
|
|
|
public final class DOMUtils {
|
|
private DOMUtils() {
|
|
}
|
|
|
|
|
|
/**
|
|
* Given a DOM element with one and only one child of text node type, returns the text as a string. If there is no
|
|
* such node, '?' is returned
|
|
* Get a string from an element (XML parsing stuff)
|
|
*
|
|
* @param e the element
|
|
* @return the text as string, or '?'
|
|
*/
|
|
public static String getInnerText(final Element e) {
|
|
final Node child = e.getFirstChild();
|
|
return child instanceof CharacterData ? ((CharacterData) child).getData() : "?";
|
|
}
|
|
|
|
public static String getInnerTextByTagName(final Element element, final String elementName) {
|
|
return getInnerTextByTagName(element, elementName, Optional.empty());
|
|
}
|
|
|
|
public static String getInnerTextByTagName(final Element element,
|
|
final String name,
|
|
final String defaultValue) {
|
|
return getInnerTextByTagName(element, name, Optional.of(defaultValue));
|
|
}
|
|
|
|
public static String getInnerTextByTagName(final Element element,
|
|
final String elementName,
|
|
final Optional<String> defaultValue) {
|
|
final NodeList field = element.getElementsByTagName(elementName);
|
|
|
|
if (field.getLength() == 0) {
|
|
return defaultValue.orElseThrow(() ->
|
|
new IllegalArgumentException(elementName + " element count in container is not 1"));
|
|
}
|
|
|
|
final Node first = field.item(0);
|
|
if (!(first instanceof Element)) {
|
|
// the contract of getElementsByTagName states that it returns a list of Element objects
|
|
throw new IllegalStateException("unreachable");
|
|
}
|
|
|
|
return getInnerText((Element) first);
|
|
}
|
|
|
|
public static List<Element> childrenElements(final Element parent) {
|
|
final List<Element> elements = new ArrayList<>();
|
|
final NodeList children = parent.getChildNodes();
|
|
for (int i = 0; i < children.getLength(); i++) {
|
|
final Node item = children.item(i);
|
|
if (item instanceof Element) {
|
|
elements.add((Element) item);
|
|
}
|
|
}
|
|
return elements;
|
|
}
|
|
}
|