private static Xpp3Dom createExpectedDom() { Xpp3Dom expectedDom = new Xpp3Dom("root"); Xpp3Dom el1 = new Xpp3Dom("el1"); el1.setValue("element1"); expectedDom.addChild(el1); Xpp3Dom el2 = new Xpp3Dom("el2"); el2.setAttribute("att2", "attribute2\nnextline"); expectedDom.addChild(el2); Xpp3Dom el3 = new Xpp3Dom("el3"); el3.setAttribute("att3", "attribute3"); el3.setValue("element3"); el2.addChild(el3); Xpp3Dom el4 = new Xpp3Dom("el4"); el4.setValue(""); expectedDom.addChild(el4); Xpp3Dom el5 = new Xpp3Dom("el5"); expectedDom.addChild(el5); Xpp3Dom el6 = new Xpp3Dom("el6"); el6.setAttribute("xml:space", "preserve"); el6.setValue(" do not trim "); expectedDom.addChild(el6); return expectedDom; }
public static Xpp3Dom build(XmlPullParser parser, boolean trim) throws XmlPullParserException, IOException { List<Xpp3Dom> elements = new ArrayList<Xpp3Dom>(); List<StringBuilder> values = new ArrayList<StringBuilder>(); int eventType = parser.getEventType(); boolean spacePreserve = false; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { spacePreserve = false; String rawName = parser.getName(); Xpp3Dom childConfiguration = new Xpp3Dom(rawName); int depth = elements.size(); if (depth > 0) { Xpp3Dom parent = elements.get(depth - 1); parent.addChild(childConfiguration); } elements.add(childConfiguration); if (parser.isEmptyElementTag()) { values.add(null); } else { values.add(new StringBuilder()); } int attributesSize = parser.getAttributeCount(); for (int i = 0; i < attributesSize; i++) { String name = parser.getAttributeName(i); String value = parser.getAttributeValue(i); childConfiguration.setAttribute(name, value); spacePreserve = spacePreserve || ("xml:space".equals(name) && "preserve".equals(value)); } } else if (eventType == XmlPullParser.TEXT) { int depth = values.size() - 1; @SuppressWarnings("MismatchedQueryAndUpdateOfStringBuilder") StringBuilder valueBuffer = values.get(depth); String text = parser.getText(); if (trim && !spacePreserve) { text = text.trim(); } valueBuffer.append(text); } else if (eventType == XmlPullParser.END_TAG) { int depth = elements.size() - 1; Xpp3Dom finishedConfiguration = elements.remove(depth); /* this Object could be null if it is a singleton tag */ Object accumulatedValue = values.remove(depth); if (finishedConfiguration.getChildCount() == 0) { if (accumulatedValue == null) { finishedConfiguration.setValue(null); } else { finishedConfiguration.setValue(accumulatedValue.toString()); } } if (depth == 0) { return finishedConfiguration; } } eventType = parser.next(); } throw new IllegalStateException("End of document found before returning to 0 depth"); }