Beispiel #1
0
  private String serialize(Element e, int intent) {

    try {

      XmlSerializer s = Xml.newSerializer();
      StringWriter sw = new StringWriter();

      s.setOutput(sw);
      s.startDocument("utf-8", null);

      String spaces = null;
      if (intent > 0) {
        char[] chars = new char[intent];
        Arrays.fill(chars, ' ');
        spaces = new String(chars);
      }

      serialize(root, s, 0, spaces);
      s.endDocument();

      return sw.toString();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return null;
  }
Beispiel #2
0
  private void serialize(Element e, XmlSerializer s, int depth, String spaces) throws Exception {

    String name = e.getTagName();

    writeSpace(s, depth, spaces);

    s.startTag("", name);

    if (e.hasAttributes()) {
      NamedNodeMap nm = e.getAttributes();
      for (int i = 0; i < nm.getLength(); i++) {
        Attr attr = (Attr) nm.item(i);
        s.attribute("", attr.getName(), attr.getValue());
      }
    }

    if (e.hasChildNodes()) {

      NodeList nl = e.getChildNodes();

      int elements = 0;

      for (int i = 0; i < nl.getLength(); i++) {

        Node n = nl.item(i);

        short type = n.getNodeType();

        switch (type) {
          case Node.ELEMENT_NODE:
            serialize((Element) n, s, depth + 1, spaces);
            elements++;
            break;
          case Node.TEXT_NODE:
            s.text(text(n));
            break;
          case Node.CDATA_SECTION_NODE:
            s.cdsect(text(n));
            break;
        }
      }

      if (elements > 0) {
        writeSpace(s, depth, spaces);
      }
    }

    s.endTag("", name);
  }