com.webstersmalley.tv.sky.DOMUtilities Maven / Gradle / Ivy
/*
* Copyright 2013 Webster Smalley
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webstersmalley.tv.sky;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
/**
* Created by: Matthew Smalley
* Date: 15/04/13
*/
public class DOMUtilities {
private static Logger logger = LoggerFactory.getLogger(DOMUtilities.class);
private DOMUtilities() {
}
public static String getElementText(Document parent, String elementName) {
return getElementText(parent.getDocumentElement(), elementName);
}
public static String getElementText(Element parent, String elementName) {
NodeList list = parent.getElementsByTagName(elementName);
if (list.getLength() != 1) {
logger.debug("Expected 1 element, found: " + list.getLength());
return null;
}
Element element = (Element) list.item(0);
return element.getTextContent().trim();
}
public static Document getDocumentFromStringContent(String content) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
return dBuilder.parse(IOUtils.toInputStream(content));
} catch (ParserConfigurationException e) {
logger.error("Error converting text to document: " + e.getMessage(), e);
throw new RuntimeException("Error converting text to document: " + e.getMessage(), e);
} catch (SAXException e) {
logger.error("Error converting text to document: " + e.getMessage(), e);
throw new RuntimeException("Error converting text to document: " + e.getMessage(), e);
} catch (IOException e) {
logger.error("Error converting text to document: " + e.getMessage(), e);
throw new RuntimeException("Error converting text to document: " + e.getMessage(), e);
}
}
}