---
title: "Eclipse中Android项目XML文件的格式化配置  "
author: "cqfly"
date: "2011-10-20T12:11:29Z"
tags: []
categories: ["移动开发"]
slug: "eclipse-android-xml"
draft: false
lastmod: "2011-10-20T12:12:02Z"
id: 1203020
url: "https://cqfly.iteye.com/blog/1203020"
---

原地址：[http://rongjih.blog.163.com/blog/static/3357446120110250736914/](http://rongjih.blog.163.com/blog/static/3357446120110250736914/)

 

### Eclipse中Android项目XML文件的格式化配置

2011-01-25 13:03:16|  分类： [Android](http://rongjih.blog.163.com/blog/#m=0&t=1&c=fks_087068081080086074081082085095087085084068080082080066 "Android") |  标签：[android](http://rongjih.blog.163.com/blog/#m=0&t=3&c=android)  [xml](http://rongjih.blog.163.com/blog/#m=0&t=3&c=xml)  [格式化](http://rongjih.blog.163.com/blog/#m=0&t=3&c=%E6%A0%BC%E5%BC%8F%E5%8C%96)  [eclipse](http://rongjih.blog.163.com/blog/#m=0&t=3&c=eclipse)  |字号 [订阅]()

    在Eclipse中使用ADT开发Android很方便，但也有些不如意的地方，如XML文件的格式化效果就很不理想。默认情况下，使用ADT的可视化界面布局，自动生成的xml文件中，一个控件的配置全动挤到一行上（效果如下所示），阅读、修改起来都很不方便。

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout ...>
<TextView android:id="@+id/TextView01" android:layout_width="wrap_content" ...></TextView>
</LinearLayout>
```

而我希望最佳的格式化效果如下，控件的每个属性配置占一行方便阅读修改，没有子元素的控件直接使用 /&gt; 关闭：

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/TextView01"
        android:text="Some Content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
```

    为了达到上述的格式化效果，需要修改Eclipse的一些配置及进行一些额外的操作：

**1）修改Eclipse的XML格式化配置**

    这一步的配置是使格式化的效果为控件的每个属性配置占一行。进入 Window/Preferences，展开到 XML/XML Files/Editor，

勾选 “Split multiple attributes each on a new line” 即可，如下图所示：

![Eclipse中Android项目XML文件的格式化配置 - rongjih - 拥有自己的梦想，跟随心的召唤](http://img617.ph.126.net/l8KN1Lk0WhrCe4s8ETOBuw==/1902770842565720945.jpg)

经此配置后，每次使用快捷键  Ctrl+Shift+F 键格式化后每个属性配置就会占一行。

**2）压缩节点的声明方式**

    这步的目的是将没有子节点的元素的声明方式进行压缩，如将 “&lt;TextView ...&gt;&lt;/TextView&gt;” 转化为 “&lt;TextView .../&gt;”。

方法为在XML文件内空白地方点击鼠标右键，选择 ”Source/Cleanup Document...“，如下图所示：

![Eclipse中Android项目XML文件的格式化配置 - rongjih - 拥有自己的梦想，跟随心的召唤](http://img851.ph.126.net/39VPA63L0IzAwAY5jjuKYQ==/589971551186569658.jpg)

 之后将弹出如下界面：

![Eclipse中Android项目XML文件的格式化配置 - rongjih - 拥有自己的梦想，跟随心的召唤](http://img233.ph.126.net/kGZR21m_ZlssQ_nAx6dbXA==/1746552230491149103.png)

勾选“Compress empty element tags”，点击 OK 按钮即可。 

为了方便，可以为此操作添加一个快捷键，进入 Window/Preferences，展开到 General/Keys，如下图配置自己喜欢的快捷键即可：

![Eclipse中Android项目XML文件的格式化配置 - rongjih - 拥有自己的梦想，跟随心的召唤](http://img229.ph.126.net/QYTWa6z8JcqZEY7aH_228Q==/2148779972211107243.png)