001: /*
002: * Copyright (C) 2004, 2005 Joe Walnes.
003: * Copyright (C) 2006, 2007 XStream Committers.
004: * All rights reserved.
005: *
006: * The software in this package is published under the terms of the BSD
007: * style license a copy of which has been included with this distribution in
008: * the LICENSE.txt file.
009: *
010: * Created on 07. March 2004 by Joe Walnes
011: */
012: package com.thoughtworks.xstream.io.xml.xppdom;
013:
014: import org.xmlpull.mxp1.MXParser;
015: import org.xmlpull.v1.XmlPullParser;
016:
017: import java.io.Reader;
018: import java.util.ArrayList;
019: import java.util.List;
020:
021: public class Xpp3DomBuilder {
022: public static Xpp3Dom build(Reader reader) throws Exception {
023: List elements = new ArrayList();
024:
025: List values = new ArrayList();
026:
027: Xpp3Dom node = null;
028:
029: XmlPullParser parser = new MXParser();
030:
031: parser.setInput(reader);
032:
033: int eventType = parser.getEventType();
034:
035: while (eventType != XmlPullParser.END_DOCUMENT) {
036: if (eventType == XmlPullParser.START_TAG) {
037: String rawName = parser.getName();
038:
039: Xpp3Dom child = new Xpp3Dom(rawName);
040:
041: int depth = elements.size();
042:
043: if (depth > 0) {
044: Xpp3Dom parent = (Xpp3Dom) elements.get(depth - 1);
045:
046: parent.addChild(child);
047: }
048:
049: elements.add(child);
050:
051: values.add(new StringBuffer());
052:
053: int attributesSize = parser.getAttributeCount();
054:
055: for (int i = 0; i < attributesSize; i++) {
056: String name = parser.getAttributeName(i);
057:
058: String value = parser.getAttributeValue(i);
059:
060: child.setAttribute(name, value);
061: }
062: } else if (eventType == XmlPullParser.TEXT) {
063: int depth = values.size() - 1;
064:
065: StringBuffer valueBuffer = (StringBuffer) values
066: .get(depth);
067:
068: valueBuffer.append(parser.getText());
069: } else if (eventType == XmlPullParser.END_TAG) {
070: int depth = elements.size() - 1;
071:
072: Xpp3Dom finalNode = (Xpp3Dom) elements.remove(depth);
073:
074: String accumulatedValue = (values.remove(depth))
075: .toString();
076:
077: String finishedValue;
078:
079: if (0 == accumulatedValue.length()) {
080: finishedValue = null;
081: } else {
082: finishedValue = accumulatedValue;
083: }
084:
085: finalNode.setValue(finishedValue);
086:
087: if (0 == depth) {
088: node = finalNode;
089: }
090: }
091:
092: eventType = parser.next();
093: }
094:
095: reader.close();
096:
097: return node;
098: }
099:
100: }
|