from xml.sax.saxutils import quoteattr


def xmlattrstr(attrs):
    """Construct an XML-safe attribute string from the given attributes

        "attrs" is a dictionary of attributes

    The returned attribute string includes a leading space, if necessary,
    so it is safe to use the string right after a tag name.
    """
    # XXX Should this be using
    s = ''
    names = attrs.keys()
    names.sort()  # dump attrs sorted by key, not necessary but is more stable
    for name in names:
        s += ' %s=%s' % (name, quoteattr(str(attrs[name])))
    return s