JAVA动态修改xml文件

写这个是因为之前维护一个老的项目,项目中有涉及到一个轮播图,使用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();
		}
	}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值