为Eclipse创建Ant的build.xml文件编辑自动提示

Eclipse中编辑XML配置文件的时候我们总是习惯于既有的自动提示和和完成功能,事实上它是因为有了DTD的句法约束,特定功能的XML文件都有特定的DTD头来验证和约束句法,而普通的XML文件则没有这种优待。

JavaEE版的Eclipse自动集成了Ant插件,但是,并没有提供Ant的DTD文件。原因在Apache官网的Ant项目下的FAQ中有解释,原文如下:

Is there a DTD that I can use to validate my build files?

An incomplete DTD can be created by the <antstructure> task - but this one has a few problems:

  • It doesn't know about required attributes. Only manual tweaking of this file can help here.
  • It is not complete - if you add new tasks via <taskdef> it won't know about it. See this page by Michel Casabianca for a solution to this problem. Note that the DTD you can download at this page is based on Apache Ant 0.3.1.
  • It may even be an invalid DTD. As Ant allows tasks writers to define arbitrary elements, name collisions will happen quite frequently - if your version of Ant contains the optional <test> and <junit> tasks, there are two XML elements named test (the task and the nested child element of <junit>) with different attribute lists. This problem cannot be solved; DTDs don't give a syntax rich enough to support this.
一言概之就是说DTD并不完善,功能上问题多多,但是仍然给了我们自己手动生成DTD的工具<antstructure>,对我们而言,不完善的工具也好过没有。

具体的完成步骤看一下操作:

1、先在任意一个位置创建一个build.xml文件:
<?version="1.0" encoding="UTF-8"?>

<project name="antdtd">

    <target name="makeantdtd" basedir=".">

        <antstructure output="ant.dtd" />

    </target>

</project>


2、从Apache官网的commons项目下的download找到net的jar文件下载,commons-net-3.1.jar需要jave1.5 or later的支持。将commons-net-3.1.jar拷贝到%ANT_HOIME%下的lib目录下。

3、cmd进入build.xml所在目录,执行ant命令,就会在当前目录下生成ant.dtd文件。如果没有commons-net-3.1.jar,会出现java.lang.ClassNotFoundException: org.apache.commons.net.ftp.FTPClientConfig异常。

4、拷贝ant.dtd到任意位置保存,建议放在%ANT_HOME%下的etc目录下。在Eclipse中添加DTD:Window-Preference-XML--XML Catalog,选择添加,location指定到保存ant.dtd的位置,Key Type:Public ID,Key:任意指定,如ant_DTD。

5、在Eclipse中某项目下新建XML文件,通过指定DTD生成build.xml,发现问题。在Problems View中查看,有既定问题(如果用的是commons-net-1.4.jar可能问题会不同)。根据提示[Element type "target" must not be declared more than once.   line2431],找到ant.dtd的2431行,去掉<!ELEMENT target EMPTY>即可.在build.xml中右键validate,问题消失,OK。



你可能感兴趣的:(build.xml)