首页 > 编程语言 > 详细

JAVA将list转化为xml文件

时间:2014-03-26 19:02:38      阅读:734      评论:0      收藏:0      [点我收藏+]

pojo类:

public class TreeNode {
	private int id;
	private String nodeId;
	private String parentId;
	private String hrefAddress;
	private String nodeName;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getNodeId() {
		return nodeId;
	}

	public void setNodeId(String nodeId) {
		this.nodeId = nodeId;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public String getHrefAddress() {
		return hrefAddress;
	}

	public void setHrefAddress(String hrefAddress) {
		this.hrefAddress = hrefAddress;
	}

	public String getNodeName() {
		return nodeName;
	}

	public void setNodeName(String nodeName) {
		this.nodeName = nodeName;
	}

}

将list转化为xml形式的字符串的工具类:

public class TreeUtil {
    /**
     * 根据节点数据集合,生成XML
     * @param treeNodes 权节点集合
     * @return
     */
    public String parseNodeToXML(List<TreeNode> treeNodes) {
        StringBuffer xmlnodes = new StringBuffer();
        if (treeNodes != null && treeNodes.size() > 0) {
            xmlnodes.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            xmlnodes.append("<nodes>");
            for (int i = 0; i < treeNodes.size(); i++) {
                TreeNode node = treeNodes.get(i);
                xmlnodes.append("<node nodeId=‘" + node.getNodeId() + "‘ parentId=‘" + node.getParentId()
                        + "‘ hrefAddress=‘" + node.getHrefAddress() + "‘>" + node.getNodeName() + "</node>");
            }
            xmlnodes.append("</nodes>");
        }

        return xmlnodes.toString();
    }
} 

将字符串写入到文件中:

public static void main(String[] args) throws Exception {
        List<TreeNode> list = new ArrayList<TreeNode>();

        for (int i = 0; i < 5; i++) {
            TreeNode treeNode = new TreeNode();
            treeNode.setHrefAddress("hrefAddress" + i);
            treeNode.setId(i);
            treeNode.setNodeId("nodeId" + i);
            treeNode.setNodeName("nodeName" + i);
            treeNode.setParentId("parentId" + i);
            list.add(treeNode);
        }

        String xmlFile = new TreeUtil().parseNodeToXML(list);

        FileWriter writer = new FileWriter("F:/node.xml");

        writer.write(xmlFile);
        writer.flush();
        writer.close();
        System.out.println("写入完成!");
    }

最终xml文件的形式如:bubuko.com,布布扣


JAVA将list转化为xml文件,布布扣,bubuko.com

JAVA将list转化为xml文件

原文:http://blog.csdn.net/zl544434558/article/details/22173013

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!