コード例 #1
0
  private void printOpenElementTag(int depth, Node node) {
    Element element = (Element) node;
    if (newlineBeforeElementOpen(element, depth)) {
      mOut.append(mLineSeparator);
    }
    if (indentBeforeElementOpen(element, depth)) {
      indent(depth);
    }
    mOut.append('<').append(element.getTagName());

    NamedNodeMap attributes = element.getAttributes();
    int attributeCount = attributes.getLength();
    if (attributeCount > 0) {
      // Sort the attributes
      List<Attr> attributeList = new ArrayList<Attr>();
      for (int i = 0; i < attributeCount; i++) {
        attributeList.add((Attr) attributes.item(i));
      }
      Comparator<Attr> comparator = mPrefs.getAttributeComparator();
      if (comparator != null) {
        Collections.sort(attributeList, comparator);
      }

      // Put the single attribute on the same line as the element tag?
      boolean singleLine =
          mPrefs.oneAttributeOnFirstLine && attributeCount == 1
              // In resource files we always put all the attributes (which is
              // usually just zero, one or two) on the same line
              || mStyle == XmlFormatStyle.RESOURCE;

      // We also place the namespace declaration on the same line as the root element,
      // but this doesn't also imply singleLine handling; subsequent attributes end up
      // on their own lines
      boolean indentNextAttribute;
      if (singleLine || (depth == 0 && XMLNS.equals(attributeList.get(0).getPrefix()))) {
        mOut.append(' ');
        indentNextAttribute = false;
      } else {
        mOut.append(mLineSeparator);
        indentNextAttribute = true;
      }

      Attr last = attributeList.get(attributeCount - 1);
      for (Attr attribute : attributeList) {
        if (indentNextAttribute) {
          indent(depth + 1);
        }
        mOut.append(attribute.getName());
        mOut.append('=').append('"');
        XmlUtils.appendXmlAttributeValue(mOut, attribute.getValue());
        mOut.append('"');

        // Don't add a newline at the last attribute line; the > should
        // immediately follow the last attribute
        if (attribute != last) {
          mOut.append(singleLine ? " " : mLineSeparator); // $NON-NLS-1$
          indentNextAttribute = !singleLine;
        }
      }
    }

    boolean isClosed = isEmptyTag(element);

    // Add a space before the > or /> ? In resource files, only do this when closing the
    // element
    if (mPrefs.spaceBeforeClose
        && (mStyle != XmlFormatStyle.RESOURCE || isClosed)
        // in <selector> files etc still treat the <item> entries as in resource files
        && !TAG_ITEM.equals(element.getTagName())
        && (isClosed || element.getAttributes().getLength() > 0)) {
      mOut.append(' ');
    }

    if (isClosed) {
      mOut.append('/');
    }

    mOut.append('>');

    if (newlineAfterElementOpen(element, depth, isClosed)) {
      mOut.append(mLineSeparator);
    }
  }