---
title: "Properties文件的XML格式"
author: "wxyfighting"
date: "2013-06-12T09:11:00Z"
tags: []
slug: "properties-xml"
draft: false
lastmod: "2013-06-12T14:33:08Z"
id: 1885602
url: "https://wxyfighting.iteye.com/blog/1885602"
---

想必大家都用过\*.properties文件，作为配置文件。但是，如果该文件写入了中文，待编译后内容就会成为乱码，使用native命令也好、使用ant执行编码转换也好，多少有点麻烦，与其如此，我们不如直接使用properties的xml格式。

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. &lt;?xmlversion="1.0"encoding="UTF-8"?&gt;
02. &lt;!DOCTYPEpropertiesSYSTEM"http://java.sun.com/dtd/properties.dtd"&gt;
03. &lt;properties&gt;
04. &lt;comment&gt;系统配置&lt;/comment&gt;
05. &lt;entry
06. key="logo.location"&gt;&lt;!\[CDATA\[/image/logo/]]&gt;&lt;/entry&gt;
07. &lt;entry
08. key="mail.host"&gt;&lt;!\[CDATA\[webmaster@zlex.org]]&gt;&lt;/entry&gt;
09. &lt;entry
10. key="site.name"&gt;&lt;!\[CDATA\[zlex中文网站]]&gt;&lt;/entry&gt;
11. &lt;entry
12. key="welcome"&gt;&lt;!\[CDATA\[欢迎您，{0}！]]&gt;&lt;/entry&gt;
13. &lt;/properties&gt;

对应原有的properties文件

Properties代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. #系统配置
2. logo.location=/image/logo/
3. mail.host=webmaster@zlex.org
4. site.name=zlex中文网站
5. welcome=欢迎您，{0}！

这里需要替换{0}，可以使用MessageFormat，参考如下代码：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. privateFileInputStreamfis;
02. @Before
03. publicvoidinit(){
04. try{
05. fis=newFileInputStream(newFile("config.xml"));
06. }catch(Exceptione){
07. e.printStackTrace();
08. fail(e.getMessage());
09. }
10. }
11. @Test
12. publicvoidt(){
13. Propertiesproperties=newProperties();
14. try{
15. properties.loadFromXML(fis);
16. System.err.println(MessageFormat.format(
17. (String)properties.get("welcome"),"snowolf"));
18. }catch(Exceptione){
19. e.printStackTrace();
20. fail(e.getMessage());
21. }
22. }

得到控制台输出：

引用

欢迎您，snowolf！

![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)

因为使用XML格式，不受系统编译影响，不存在中文问题！