/**
   * Get the index of a tag. Grabs the parent tag, and iterates it's children to find out what the
   * index of the tag passed in should be
   */
  private int getIndexOfTag(MXMLTagData tag) {
    MXMLTagData parent = tag.getParentTag();

    int index = 0;
    for (MXMLTagData d = parent.getFirstChild(true); d != null; d = d.getNextSibling(true)) {
      if (d == tag) break;
      else if (d.getName().equals(tag.getName())) ++index;
    }
    return index;
  }
  /**
   * Process an MXMLTagData - this will write a String representation of the tag into the
   * StringWriter passed in. This will strip out any databinding expressions from the String, TODO:
   * databinding - add the databinding expressions as children of the MXMLXMLNode, and also record
   * what the TODO: target expressions for those are (these are the expressions to set the value in
   * the XML object when the TODO: PropertyChange event fires).
   */
  void processNode(MXMLTagData tag, StringWriter sw) {
    sw.write('<');
    if (tag.isCloseTag()) sw.write('/');
    sw.write(tag.getName());
    String tagPrefix = tag.getPrefix();

    // lookup the prefix in case it's defined elsewhere in the document outside the XML tag
    if (tagPrefix != null) lookupPrefix(tagPrefix, tag);

    List<MXMLTagAttributeData> attrs = getAttributes(tag);
    for (MXMLTagAttributeData attr : attrs) {
      sw.write(' ');
      sw.write(attr.getName());
      sw.write('=');
      sw.write('"');
      sw.write(attr.getRawValue());
      sw.write('"');

      // lookup the prefix in case it's defined outside the XML tag
      String prefix = attr.getPrefix();
      if (prefix != null) lookupPrefix(prefix, tag);
    }

    StringWriter childrenSW = new StringWriter();
    for (MXMLUnitData unit = tag.getFirstChildUnit();
        unit != null;
        unit = unit.getNextSiblingUnit()) {
      processNode(unit, childrenSW);
    }

    if (tag == rootTag) {
      // If we're the root tag, then add an xmlns for each prefix that was referenced by one of our
      // children, but was defined elsewhere in the document (like in the Application tag).
      for (String prefix : referencedPrefixes) {
        String uri = externalPrefixes.getNamespaceForPrefix(prefix);
        if (uri != null) {
          sw.write(" xmlns:");
          sw.write(prefix);
          sw.write("=\"");
          sw.write(uri);
          sw.write('\"');
        }
      }
    }
    if (tag.isEmptyTag()) {
      sw.write("/>");
    } else {
      sw.write('>');
    }
    sw.write(childrenSW.toString());

    MXMLTagData endTag = tag.findMatchingEndTag();
    if (endTag != null) {
      processNode(endTag, sw);
    }
  }