Java tutorial
//package com.java2s; /** * Licensed to Apereo under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright ownership. Apereo * licenses this file to you 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 the * following location: * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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. */ import java.io.StringWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Element; import org.w3c.dom.Node; public class Main { private static final TransformerFactory transformerFactory = TransformerFactory.newInstance(); public static String getElementText(Element e) { final StringBuilder val = new StringBuilder(); for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) { if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) { val.append(n.getNodeValue()); } } return val.toString(); } public static String toString(Node node) { final Transformer identityTransformer; try { identityTransformer = transformerFactory.newTransformer(); } catch (TransformerConfigurationException e) { throw new RuntimeException("Failed to create identity transformer to serialize Node to String", e); } identityTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); final StringWriter outputWriter = new StringWriter(); final StreamResult outputTarget = new StreamResult(outputWriter); final DOMSource xmlSource = new DOMSource(node); try { identityTransformer.transform(xmlSource, outputTarget); } catch (TransformerException e) { throw new RuntimeException("Failed to convert Node to String using Transformer", e); } return outputWriter.toString(); } public static String toString(XMLEvent event) { final StringWriter writer = new StringWriter(); try { event.writeAsEncodedUnicode(writer); } catch (XMLStreamException e) { writer.write(event.toString()); } return writer.toString(); } }