用dom4j创建plist

plist文件广泛使用在Mac系统上,iPhone程序也在很多地方直接操作该文件。该文件类型实际上就是个XML,而且格式相当简单一致,这里给文件结构给出讲解,也顺便复习一下快忘光的java。

 

首先plist是xml,版本1.0,字符集始终采用utf-8,然后DOCTYPE是plist,publicID和systemID也是固定的值,然后就是标准的plist节点,这个节点将视为根节点,对应在plist视图中的Root,注意根节点有一个属性是version,一般是1.0。

 

每个节点,包括根节点都有其类型,分容器型和值型,容器型有DICTIONARY和ARRAY,DICTIONARY就是键值对应,ARRAY就是简单罗列;值型则有BOOLEAN,DATE,DATA,NUMBER,STRING。对应到xml文件中,DICTIONARY简写成dict,ARRAY还是写成array,BOOLEAN只有true和false两个值,其他的都顾名思义。

 

那么层次关系也是很明确的,只有容器型才能有下层,值形只能做容器类里的子项,如果是dict类型,则必须填写键的名字和值的内容,反应到xml文件里就是<key>xxx</key><string>yyy</string>,当然后一个string完全可能是</false>等其他类型。而array里的子项则没有键的名字,直接依次写<string>xxx</string>即可,然后那些项就会被取名为Item 1之类。同时容器型的子项完全可以是容器型,层层包裹都没关系。

 

修正一下,原来的代码有些问题,用FileWriter使用的是系统默认编码,与OutputFormat制定的utf-8无关,改为OutputStream

 

String pListPath = "/temp2.pList";
String xmlPath = "/en error_code.xml";
		
File inputXml=new File(xmlPath);
OutputFormat format = new OutputFormat("  ", true, "utf-8");
Document listDoc = DocumentHelper.createDocument();   
listDoc.setXMLEncoding("utf-8");
DocumentFactory documentFactory=new DocumentFactory();
DocumentType documentType=documentFactory.createDocType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd");
listDoc.setDocType(documentType);
Element pB = listDoc.addElement("plist");
pB.addAttribute("version", "1.0");
Element di = pB.addElement("dict");
SAXReader saxReader = new SAXReader();
try
{   
	Document readDoc = saxReader.read(inputXml);
	Element employees = readDoc.getRootElement();   
	for(Iterator i = employees.elementIterator(); i.hasNext();)
	{   
		Element employee = (Element) i.next();
		Element key = di.addElement("key");
		key.setText(employee.attributeValue("name").replaceAll("e", "KEY_ERROR_CODE_"));
		Element st = di.addElement("string");
		st.setText(employee.getTextTrim());
	}
        OutputStream fos = new FileOutputStream(pListPath);    
        XMLWriter xmlWriter=new XMLWriter(fos, format);   
	xmlWriter.write(listDoc);   
	xmlWriter.close();
}
catch (DocumentException e)
{   
	e.printStackTrace();   
}
catch (IOException e)
{
	e.printStackTrace();
}

 随手写了个把xml里面的错误代码转到plist里的方法,随便看看。

你可能感兴趣的:(xml)