写这个是因为之前维护一个老的项目,项目中有涉及到一个轮播图,使用flash做的,是写死在xml中,然后读取这个xml文件,后边需求要求这个轮播图可以在管理平台维护,因为涉及到老项目的维保合同快要到期,所以就不打算大改,只实现可以维护轮播图功能,至于flash马上要被抛弃了,咱也管不着,所以就这样写了,因为这个是xml文件只有一级节点,所以简单了
读取
public static String readFile(String xmlpath) {
String fileText = "";
try {
// 网络读取
URL url = new URL(xmlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
DataInputStream input = new DataInputStream(conn.getInputStream());
InputStreamReader isr = new InputStreamReader(input, "utf-8");
// 本地读取
FileInputStream fis = new FileInputStream("D:\\aa.xml");
InputStreamReader isr = new InputStreamReader(fis, "utf-8");
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
fileText += line;
fileText += "\r\n";
}
} catch (Exception e) {
e.printStackTrace();
}
return fileText;
}
读取-------修改-------替换
public static void modifyBannerXml(String id, String imgURL, String url) {
String filePath = ServletActionContext.getServletContext().getRealPath("/banner");
File file = new File(filePath + "/index.xml");
try {
// 创建文档解析的对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// 解析文档,形成文档树,也就是生成Document对象,此处这个file也可以http的url
Document document = builder.parse(file);
// 获得根节点
Element rootElement = document.getDocumentElement();
// 获得根节点下的所有子节点
NodeList data = rootElement.getChildNodes();
for (int i = 0; i < data.getLength(); i++) {
Node childNode = data.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element) childNode;
if (id.equals(childElement.getAttribute("id"))) {
childElement.setAttribute("imgURL", imgURL);
childElement.setAttribute("url", url);
break;
}
}
}
// 获得Transformer对象,用于输出文档
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// 封装成DOMResource对象
DOMSource domSource = new DOMSource(document);
Result result = new StreamResult(filePath + "/index.xml");
// 输出结果
transformer.transform(domSource, result);
} catch (Exception e) {
e.printStackTrace();
}
}