【Dom4j】 解析并修改XML文件


public class Test
{


/**
* 解析并修改log4j.xml 中指定的属性值
 */
private void setPriority(String fileName, String priorityValue)
{

		try
		{
			File inputXml = new File(fileName);
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			Element employees = document.getRootElement();
			for (Iterator i = employees.elementIterator(); i.hasNext();)
			{
				Element employee = (Element) i.next();
				if ("logger".equals(employee.getName()))
				{
					for (Iterator j = employee.elementIterator(); j.hasNext();)
					{
						Element node = (Element) j.next();
						if ("level".equals(node.getName()))
						{
							node.attribute("value").setValue(PriorityValue);
							break;
						}
					}
				}
			}
			OutputFormat format = OutputFormat.createPrettyPrint();
			OutputStream out = new FileOutputStream(new File(fileName));
			format.setEncoding("UTF-8");
			format.setIndent("    ");
			format.setNewlines(true);
			XMLWriter output = new XMLWriter(out, format);
			output.write(document);
			output.close();
		}
		catch (Exception e)
		{
			if (log.isErrorEnabled())
			{
				log.error("修改log4j.xml配置文件失败!文件路径:" + fileName, e);
			}
		}
}


public static void main(String args[]) throws Exception
{
    Test test = new Test();
    String fileName = "c:/log4j.xml";
    String priorityValue = "DEBUG";
    test.setPriority(fileName,priorityValue);  
}

}




你可能感兴趣的:(Java dom4j)