001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.converter.jaxp;
018 import org.w3c.dom.Attr;
019 import org.w3c.dom.Document;
020 import org.w3c.dom.Element;
021 import org.w3c.dom.Node;
022 import org.w3c.dom.NodeList;
023 import org.w3c.dom.Text;
024 import org.apache.camel.Converter;
025
026
027 /**
028 * Converts from some DOM types to Java types
029 *
030 * @version $Revision: 36321 $
031 */
032 @Converter
033 public final class DomConverter {
034 private DomConverter() {
035 // Utility Class
036 }
037 @Converter
038 public static String toString(NodeList nodeList) {
039 StringBuffer buffer = new StringBuffer();
040 append(buffer, nodeList);
041 return buffer.toString();
042 }
043
044 /*
045 @Converter
046 public static String toString(Node node) {
047 StringBuffer buffer = new StringBuffer();
048 append(buffer, node);
049 return buffer.toString();
050 }
051 */
052
053 protected static void append(StringBuffer buffer, NodeList nodeList) {
054 int size = nodeList.getLength();
055 for (int i = 0; i < size; i++) {
056 append(buffer, nodeList.item(i));
057 }
058 }
059
060 protected static void append(StringBuffer buffer, Node node) {
061 if (node instanceof Text) {
062 Text text = (Text) node;
063 buffer.append(text.getTextContent());
064 } else if (node instanceof Attr) {
065 Attr attribute = (Attr) node;
066 buffer.append(attribute.getTextContent());
067
068 } else if (node instanceof Element) {
069 Element element = (Element) node;
070 append(buffer, element.getChildNodes());
071 } else if (node instanceof Document) {
072 Document doc = (Document) node;
073 append(buffer, doc.getChildNodes());
074 }
075 }
076 }