public byte[] toByteArray() throws IOException {

        int size = 8 + prepare();
        ByteBuffer out = ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN);

        out.putInt(RES_XML_TYPE | (0x0008 << 16));
        out.putInt(size);

        int stringSize = this.stringItems.getSize();
        int padding = 0;
        if (stringSize % 4 != 0) {
            padding = 4 - stringSize % 4;
        }
        out.putInt(RES_STRING_POOL_TYPE | (0x001C << 16));
        out.putInt(stringSize + padding + 8);
        this.stringItems.write(out);
        out.put(new byte[padding]);

        out.putInt(RES_XML_RESOURCE_MAP_TYPE | (0x0008 << 16));
        out.putInt(8 + this.resourceIds.size() * 4);
        for (Integer i : resourceIds) {
            out.putInt(i);
        }

        Stack<Ns> stack = new Stack<Ns>();
        for (Map.Entry<String, Ns> e : this.nses.entrySet()) {
            Ns ns = e.getValue();
            stack.push(ns);
            out.putInt(RES_XML_START_NAMESPACE_TYPE | (0x0010 << 16));
            out.putInt(24);
            out.putInt(-1);
            out.putInt(0xFFFFFFFF);
            out.putInt(ns.prefix.index);
            out.putInt(ns.uri.index);
        }

        for (NodeImpl first : firsts) {
            first.write(out);
        }

        while (stack.size() > 0) {
            Ns ns = stack.pop();
            out.putInt(RES_XML_END_NAMESPACE_TYPE | (0x0010 << 16));
            out.putInt(24);
            out.putInt(ns.ln);
            out.putInt(0xFFFFFFFF);
            out.putInt(ns.prefix.index);
            out.putInt(ns.uri.index);
        }
        return out.array();
    }
a class to write android axml

@author <a href="mailto:pxb1988@gmail.com">Panxiaobo</a>
android/third_party/apkbuilder/src/main/java/pxb/android/axml/AxmlWriter.java