生成xml树Java
1,首先是一个基类BaseNode,封装了Node类,并且定义了所需属性的添加方法,注意Id属性:
import org.w3c.dom.*; public class BaseNode { public BaseNode(Node d) { id = null; node = d; } public Node getNode() { return node; } protected Node addAttribute(String attrName,String attrValue) { if(attrValue == null) attrValue = ""; if(attrName.equalsIgnoreCase("id")) id = attrValue; Attr _attr = node.getOwnerDocument().createAttribute(attrName); _attr.setNodeValue(attrValue); return node.getAttributes().setNamedItem(_attr); } public void addLabel(String attrValue) { addAttribute("label",attrValue); } public void addTitle(String attrValue) { addAttribute("title",attrValue); } public void addExtInfo(String attrValue) { addAttribute("extinfo",attrValue); } public String getID() { return id; } public void addChecked(String attrValue) { addAttribute("checked",attrValue); } protected Node node; private String id; } 2,定义子类TreeNode: import org.w3c.dom.Node; // Referenced classes of package com.neusoft.unieap.util.tree: // BaseNode public class TreeNode extends BaseNode { public TreeNode(Node d) { super(d); } public void addLink(String attrValue) { addAttribute("link",attrValue); } } 3,定义子类Tree,注意Tree与TreeNode之间无继承关系,它们都只代表xml中不同类型的节点: public class Tree extends BaseNode { public Tree(Node d) { super(d); } public TreeNode newTreeNode(String id) { TreeNode _node = new TreeNode(getNode().getOwnerDocument().createElement("TreeNode")); getNode().appendChild(_node.getNode()); String _id = id; _node.addAttribute("id",_id); return _node; } public Tree newTree(String id) { Tree _node = new Tree(getNode().getOwnerDocument().createElement("Tree")); getNode().appendChild(_node.getNode()); String _id = id; _node.addAttribute("id",_id); return _node; } } 4,定义子类Trees: public class Trees extends BaseNode { public Trees(String id) { super(null); xml_id = null; treeType = "CommonTree"; Document doc = DOMTool.createNewDocument(); node = DOMTool.createAndAppendElement(doc,"Trees",null); xml_id = id; } public Tree newTree(String id) throws Exception { if(xml_id == null) { throw new Exception(" you must define trees's id firstly"); } else { Tree _node = new Tree(getNode().getOwnerDocument().createElement("Tree")); getNode().appendChild(_node.getNode()); String _id = id; _node.addAttribute("id",_id); return _node; } } public String getID() { return xml_id; } public void setTreeType(String treeType) { this.treeType = treeType; } public StringBuffer print() throws Exception { if(xml_id == null) throw new Exception("trees's id excepted"); StringBuffer xml = new StringBuffer(); String tmpStr = DOMTool.domToString(getNode()); tmpStr = tmpStr.substring(tmpStr.indexOf(">") + 2); xml.append("<xml id =""); xml.append(xml_id); xml.append("" ondatasetcomplete=""); if(treeType.equalsIgnoreCase("SelectTree")) xml.append("new SelectTree().init('"); else xml.append("new CommonTree().init('"); xml.append(xml_id); xml.append("');""); xml.append(">n"); xml.append(tmpStr); xml.append("n"); xml.append("</xml>"); return xml; } public static void main(String args[]) { try { Trees trees = new Trees("xml_data"); Tree tree = null; TreeNode treeNode = null; tree = trees.newTree("aa"); tree.addLabel("u6D4Bu8BD5u4E3Bu83DCu53551"); tree.addTitle("u6D4Bu8BD5u83DCu5355u6807u98981"); treeNode = tree.newTreeNode("aa1"); treeNode.addLabel("u6D4Bu8BD5u5B50u83DCu53551"); treeNode.addTitle("u6D4Bu8BD5u5B50u83DCu5355u6807u98981"); treeNode.addLink("http://www.sina.com.cn"); treeNode = tree.newTreeNode("aa2"); treeNode.addLabel("u6D4Bu8BD5u5B50u83DCu53552"); treeNode.addTitle("<u6D4Bu8BD5u5B50u83DCu5355u6807u98982>"); treeNode = tree.newTreeNode("aa3"); treeNode.addLabel("u6D4Bu8BD5u5B50u83DCu53553"); treeNode.addTitle("u6D4Bu8BD5u5B50u83DCu5355u6807u98983"); treeNode.addLink("http://www.sina.com.cn"); tree = tree.newTree("bb"); tree.addLabel("u6D4Bu8BD5u5B50u83DCu5355u4E2Du7684u5D4Cu5957u83DCu5355"); tree.addTitle("u6D4Bu8BD5u5B50u83DCu5355u4E2Du7684u5D4Cu5957u83DCu5355"); treeNode = tree.newTreeNode("bb1"); treeNode.addLabel("u6D4Bu8BD5u5B50u83DCu53551"); treeNode.addTitle("u6D4Bu8BD5u5B50u83DCu5355u6807u98981"); treeNode.addLink("http://www.sina.com.cn"); treeNode = tree.newTreeNode("bb2"); treeNode.addLabel("u6D4Bu8BD5u5B50u83DCu53552"); treeNode.addTitle("<u6D4Bu8BD5u5B50u83DCu5355u6807u98982>"); treeNode = tree.newTreeNode("bb3"); treeNode.addLabel("u6D4Bu8BD5u5B50u83DCu53553"); treeNode.addTitle("<u6D4Bu8BD5u5B50u83DCu5355u6807u98983>"); tree = trees.newTree("cc"); tree.addLabel("u6D4Bu8BD5u4E3Bu83DCu53552"); tree.addTitle("u6D4Bu8BD5u83DCu5355u6807u98982"); treeNode = tree.newTreeNode("cc1"); treeNode.addLabel("u6D4Bu8BD5u5B50u83DCu53551"); treeNode.addTitle("u6D4Bu8BD5u5B50u83DCu5355u6807u98981"); treeNode.addLink("http://www.sina.com.cn"); treeNode = tree.newTreeNode("cc2"); treeNode.addLabel("u6D4Bu8BD5u5B50u83DCu53552"); treeNode.addTitle("<u6D4Bu8BD5u5B50u83DCu5355u6807u98982>"); System.out.println(trees.print()); } catch(Exception e) { System.out.println("e is " + e); } } private String xml_id; private String treeType; } 5.新类 package test; import java.io.*; import java.util.*; import javax.xml.parsers.*; import org.apache.xerces.parsers.DOMParser; import org.xml.sax.*; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.*; import org.xml.sax.InputSource; public class DOMTool { /* member class not found */ static class ParseErrorHandler implements ErrorHandler { public void warning(SAXParseException saxparseexception) throws SAXException { } public void error(SAXParseException e) throws SAXException { throw e; } public void fatalError(SAXParseException e) throws SAXException { throw e; } ParseErrorHandler() { } } public DOMTool() { } public static Document createNewDocument() { Document document = null; try { document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();//初始化一颗DOM树 } catch(ParserConfigurationException parserconfigurationexception) { } return document; } public static Document loadDocumentFromStr(String str) { Document document = null; try { InputStream is = new ByteArrayInputStream(str.getBytes()); document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(is)); } catch(Exception exception) { } return document; } public static Document loadDocumentFromStr(String str,String charsetName) { Document document = null; try { InputStream is = new ByteArrayInputStream(str.getBytes(charsetName)); document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(is)); } catch(Exception exception) { } return document; } public static Document loadDocumentFromFile(File f) { Document document = null; try { document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f); } catch(Exception exception) { } return document; } public static Document loadDocumentFromInputStream(InputStream is) { Document document = null; try { document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); } catch(Exception exception) { } return document; } public static Document loadDocumentFromUri(String uri) { Document document = null; try { document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(uri); } catch(Exception exception) { } return document; } public static void parse(Document doc) throws Exception { DOMParser parser = new DOMParser(); //parser.setErrorHandler(new ParseErrorHandler()); parser.setFeature("http://xml.org/sax/features/validation",true); StringReader sr = new StringReader(domToString(doc)); InputSource is = new InputSource(sr); parser.parse(is); } public static void appendChild(Node node,Node subNode) { node.appendChild(subNode); } public static boolean containsNode(Node node,String tagName) { return getSingleNode(node,tagName) != null; } public static Node getSingleNode(Node node,String tagName) { if(node == null || tagName == null) return null; Node singleNode = null; NodeList nodeList = null; if(node instanceof Document) nodeList = ((Document)node).getElementsByTagName(tagName); else nodeList = ((Element)node).getElementsByTagName(tagName); if(nodeList != null && nodeList.getLength() > 0) singleNode = nodeList.item(0); return singleNode; } public static Element getSingleElement(Node node,String tagName) { Element singleElement = null; if(containsNode(node,tagName)) singleElement = (Element)getSingleNode(node,tagName); return singleElement; } public static NodeList getMultiNodes(Node node,String tagName) { if(node == null || tagName == null) return null; NodeList nodeList = null; if(node instanceof Document) nodeList = ((Document)node).getElementsByTagName(tagName); else nodeList = ((Element)node).getElementsByTagName(tagName); return nodeList; } public static Node getNode(Node node,String tagName,int offset) { if(node == null || tagName == null || offset < 0) return null; Node result = null; NodeList nodeList = getMultiNodes(node,tagName); if(offset < nodeList.getLength()) result = nodeList.item(offset); return result; } public static Element getElement(Node node,int offset) { Node result = getNode(node,tagName,offset); if(result == null) return null; else return (Element)result; } public static String getNodeValue(Node node) { if(node == null || (node instanceof Document)) return null; NodeList nodelist = node.getChildNodes(); if(nodelist.getLength() <= 0) return null; StringBuffer stringBuffer = new StringBuffer(); for(int i = 0; i < nodelist.getLength(); i++) { Node eachNode = nodelist.item(i); if(eachNode.getNodeType() == 3) stringBuffer.append(eachNode.getNodeValue()); } return stringBuffer.toString(); } public static String getSingleNodeValue(Node node,String tagName) { Node singleNode = getSingleNode(node,tagName); return getNodeValue(singleNode); } public static String[] getMultiNodeValues(Node node,String tagName) { NodeList nodeList = getMultiNodes(node,tagName); if(nodeList == null) return new String[0]; String nodeValues[] = new String[nodeList.getLength()]; for(int i = 0; i < nodeList.getLength(); i++) nodeValues[i] = getNodeValue(nodeList.item(i)); return nodeValues; } public static String getAttributeValue(Element element,String attrName) { if(element == null || attrName == null) return null; else return element.getAttribute(attrName); } public static HashMap getAttributeValues(Element element) { HashMap attributes = new HashMap(); NamedNodeMap map = element.getAttributes(); for(int i = 0; i < map.getLength(); i++) { Attr attr = (Attr)map.item(i); attributes.put(attr.getName(),attr.getValue()); } return attributes; } public static String getSingleAttributeValue(Node node,String attrName) { String attributeValue = null; Element element = getSingleElement(node,tagName); if(element != null) attributeValue = element.getAttribute(attrName); return attributeValue; } public static String[] getMultiAttributeValue(Node node,String attrName) { NodeList nodeList = getMultiNodes(node,tagName); if(nodeList == null) return new String[0]; String attributeValues[] = new String[nodeList.getLength()]; for(int i = 0; i < nodeList.getLength(); i++) attributeValues[i] = getAttributeValue((Element)nodeList.item(i),attrName); return attributeValues; } public static Element createElement(Document document,String elementName,String elementValue) { if(document == null || elementName == null) { return null; } else { Element element = document.createElement(elementName); setNodeValue(element,elementValue); return element; } } public static Element createAndAppendRoot(Document document,String elementValue) { if(document == null || elementName == null) { return null; } else { Element element = document.createElement(elementName); document.appendChild(element); setNodeValue(element,elementValue); return element; } } public static Element createAndAppendElement(Node node,String elementValue) { if(node == null || elementName == null) return null; Document document = null; if(node instanceof Document) document = (Document)node; else document = node.getOwnerDocument(); Element element = document.createElement(elementName); node.appendChild(element); setNodeValue(element,elementValue); return element; } public static void createAndAppendMultiElement(Node node,String elementValues[]) { if(node == null || elementName == null || elementValues == null || elementValues.length == 0 || (node instanceof Document)) return; Document document = node.getOwnerDocument(); for(int i = 0; i < elementValues.length; i++) { Element eachElement = document.createElement(elementName); node.appendChild(eachElement); setNodeValue(eachElement,elementValues[i]); } } public static void setNodeValue(Node node,String nodeValue) { if(node == null || (node instanceof Document)) return; Document document = node.getOwnerDocument(); NodeList nodeList = node.getChildNodes(); for(int i = 0; i < nodeList.getLength(); i++) { Node eachNode = nodeList.item(i); if(eachNode.getNodeType() == 3)//TEXT_NODE node.removeChild(eachNode); } if(nodeValue != null) node.appendChild(document.createTextNode(nodeValue));//向节点的子节点的列表的结尾添加新的子节点 } public static void setSingleNodeValue(Node node,String nodeValue) { Node singleNode = getSingleNode(node,tagName); if(singleNode != null) setNodeValue(singleNode,nodeValue); } public static void setAttribute(Element element,String attributeName,String attributeValue) { if(element != null && attributeName != null) element.setAttribute(attributeName,attributeValue); } public static void setAttributes(Element element,HashMap attributes) { if(element == null || attributes == null) return; String key; for(Iterator e = attributes.keySet().iterator(); e.hasNext(); element.setAttribute(key,attributes.get(key).toString())) key = e.next().toString(); } public static void setSingleNodeAttribute(Node node,String attributeValue) { Element element = getSingleElement(node,tagName); setAttribute(element,attributeName,attributeValue); } public static String domToString(Node node) { StringWriter stringwriter = new StringWriter(); XMLSerializer xmlserializer = new XMLSerializer(stringwriter,null); try { if(node instanceof Document) xmlserializer.serialize((Document)node); if(node instanceof Element) xmlserializer.serialize((Element)node); } catch(Exception exception) { return null; } return stringwriter.toString(); } public static Node unionNodes(Node oriNode,Node targetNode,boolean isApendChildNode) { HashMap oriAttrs = getAttributeValues((Element)oriNode); HashMap targetAttrs = getAttributeValues((Element)targetNode); String key; for(Iterator e = targetAttrs.keySet().iterator(); e.hasNext(); oriAttrs.put(key,targetAttrs.get(key))) key = e.next().toString(); setAttributes((Element)oriNode,oriAttrs); if(!isApendChildNode) return oriNode; NodeList nodelist = targetNode.getChildNodes(); int j = nodelist.getLength(); for(int i = 0; i < nodelist.getLength(); i++) if(nodelist.item(i).getNodeType() != 3) removeChildNodes(oriNode,nodelist.item(i).getNodeName()); for(int i = 0; i < nodelist.getLength(); i++) if(nodelist.item(i).getNodeType() != 3) appendChild(oriNode,nodelist.item(i)); return oriNode; } public static void removeChildNodes(Node node,String tagName) { NodeList nodelist = node.getChildNodes(); for(int i = 0; i < nodelist.getLength(); i++) if(nodelist.item(i).getNodeName().equals(tagName)) node.removeChild(nodelist.item(i)); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |