最近我们项目在做系统界面颜色配置,用java dom解析xml文件来自动生成css。我上网查了些资料,简单的把java用DOM解析XML文档的方法和实例列在文章里,供自己参考。
1. DOM(Document Object Model)
DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准。DOM是以层次结构组织的节点的集合。由于它是基于信息层次的,所以DOM被视为是基于树或基于对象的。你可以把它想象成一颗DOM树, 通过节点以及节点之间的关系操作XML文档。不过用DOM操作XML需要加载整个XML文档来构造层次结构,因此消耗资源大。
下面这个XML文件是用来生成界面css的
1 <cssStyleItems> 2 <cssItem> 3 <cssClass> 4 <element>#header</element> 5 </cssClass> 6 <inherentCss> 7 <element>margin-bottom:20px;</element> 8 <element>min-height: 70px;</element> 9 <element>padding: 28px 0px 0;</element> 10 <element>box-shadow: 0 5px 10px rgba(0, 0, 0, 0.4);</element> 11 <element>background-image: -moz-linear-gradient(top, rgba(255, 255, 255, 0.1) 0%, rgba(0, 0, 0, 0.1) 40%, rgba(0, 0, 0, 0.2) 98%, #FFFFFF 100%);</element> 12 <element>background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(255, 255, 255, 0.1)), 13 color-stop(40%, rgba(0, 0, 0, 0.1)), color-stop(98%, rgba(0, 0, 0, 0.2)),color-stop(100%, #FFFFFF));</element> 14 <element>background-image: -webkit-linear-gradient(top, rgba(255, 255, 255, 0.1) 0%, rgba(0, 0, 0, 0.1) 40%, rgba(0, 0, 0, 0.2) 98%, #FFFFFF 100%);</element> 15 <element>background-image: -o-linear-gradient(top, rgba(255, 255, 255, 0.1) 0%, rgba(0, 0, 0, 0.1) 40%, rgba(0, 0, 0, 0.2) 98%, #FFFFFF 100%);</element> 16 <element>filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr=‘#22FFFFFF‘, EndColorStr=‘#33000000‘);</element> 17 <element>background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.1) 0%, rgba(0, 0, 0, 0.1) 40%, rgba(0, 0, 0, 0.2) 98%, #FFFFFF 100%);</element> 18 </inherentCss> 19 <configCss> 20 <element cssClass_id="headerBackgroundColor">background-color:</element> 21 </configCss> 22 </cssItem> 23 <cssStyleItems>
Java调用DOM解析XML
1 package com.utils; 2 3 import java.io.BufferedWriter; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileNotFoundException; 7 import java.io.FileWriter; 8 import java.io.IOException; 9 import java.io.InputStream; 10 import java.util.Map; 11 12 import javax.xml.parsers.DocumentBuilder; 13 import javax.xml.parsers.DocumentBuilderFactory; 14 import javax.xml.parsers.ParserConfigurationException; 15 import com.bean.CssLibBean; 16 import org.slf4j.Logger; 17 import org.slf4j.LoggerFactory; 18 import org.w3c.dom.Document; 19 import org.w3c.dom.NamedNodeMap; 20 import org.w3c.dom.Node; 21 import org.w3c.dom.NodeList; 22 import org.xml.sax.SAXException; 23 24 25 public class CssStyleBuilderAdv { 26 private static final String IMPORTANT = "important"; //读取xml里important属性 27 private static final String CSS_CLASS_ID = "cssClass_id"; //读取xml里cssClass_id属性 28 private static final String CONFIG_CSS = "configCss"; //读取xml里configCss节点 29 private static final String INHERENT_CSS = "inherentCss"; //读取xml里inherentCss节点 30 private static final String CSS_CLASS = "cssClass"; //读取xml里cssClass节点 31 private static final String WRAPPER = " "; //设置空格 32 33 private Map<String, String> cssElementMap; 34 35 public CssStyleBuilderAdv(Map<String, String> cssElementMap) { 36 this.cssElementMap = cssElementMap; 37 } 38 39 40 /** 41 * 在现在的主题上解析xml生成css_build.css 42 * 43 * @return 44 */ 45 // 46 public void buildCssFile(String currentTheme) throws FileNotFoundException { 47 writeCssFile(readXMLFile(currentTheme), currentTheme); 48 } 49 50 51 /** 52 * 读取CSS template.xml 53 * 54 * @return Css build 55 */ 56 public String readXMLFile(String currentTheme) { 57 String rebuiltCss = ""; 58 DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance(); 59 try { 60 DocumentBuilder domBuilder = domfac.newDocumentBuilder(); 61 String cssTemplateUrl = SystemParameters.getConfigPath() + "/" + currentTheme + "/cssTemplate.xml"; //获取指定位置的xml 62 File file = new File(cssTemplateUrl); 63 InputStream is = new FileInputStream(file); 64 Document doc = domBuilder.parse(is); 65 NodeList cssItemList = doc.getElementsByTagName("cssItem"); //获取cssItem节点 66 if (cssItemList != null) { 67 for (int i = 0; i < cssItemList.getLength(); i++) { //遍历cssItem节点列表 68 StringBuffer cssClassList = new StringBuffer(); //定义cssItem的孩子节点cssClass列表 69 StringBuffer inherentCssList = new StringBuffer(); //定义cssItem的孩子节点inherentCss列表 70 StringBuffer configCssList = new StringBuffer(); //定义cssItem的孩子节点configCss列表 71 Node cssItem = cssItemList.item(i); 72 NodeList childNodes = cssItem.getChildNodes(); //获取cssItem的孩子列表 73 for (int j = 0; j < childNodes.getLength(); j++) { //遍历列表 74 StringBuffer cssClassItem = new StringBuffer(); 75 StringBuffer inherentCss = new StringBuffer(); 76 StringBuffer configCss = new StringBuffer(); 77 Node cssNode = childNodes.item(j); 78 if (cssNode.getNodeType() == Node.ELEMENT_NODE) { 79 NodeList elementNodes = cssNode.getChildNodes(); //如果节点等于Node.ELEMENT_NODE,获取该节点的孩子列表 80 for (int z = 0; z < elementNodes.getLength(); z++) { //遍历列表 81 Node elementNode = elementNodes.item(z); 82 if (elementNode.getNodeType() == Node.ELEMENT_NODE) { 83 if (cssNode.getNodeName().equals(CSS_CLASS)) { 84 cssClassItem.append(elementNode.getTextContent()); //将节点CSS_CLASS内容存到cssClassItem变量 85 cssClassItem.append(",\n"); 86 } 87 if (cssNode.getNodeName().equals(INHERENT_CSS)) { 88 inherentCss.append(WRAPPER); 89 inherentCss.append(elementNode.getTextContent()); //将节点INHERENT_CSS内容存到inherentCss变量 90 inherentCss.append("\n"); 91 } 92 if (cssNode.getNodeName().equals(CONFIG_CSS)) { 93 configCss = configCss.append(switchValueByAttrId(elementNode, configCss)); //将节点CONFIG_CSS内容存到configCss变量 94 } 95 } 96 } 97 cssClassList.append(cssClassItem); 98 inherentCssList.append(inherentCss); 99 configCssList.append(configCss); 100 } 101 } 102 rebuiltCss += cssClassList.toString().substring(0, cssClassList.length() - 2) + "{\n" 103 + inherentCssList + configCssList + "}\n\n"; //rebuiltCss存放生成的css 104 } 105 } 106 } catch (ParserConfigurationException e) { 107 LOGGER.warn("ParserConfigurationException : ", e); 108 } catch (FileNotFoundException e) { 109 LOGGER.warn("FileNotFoundException : ", e); 110 } catch (SAXException e) { 111 LOGGER.warn("SAXException : ", e); 112 } catch (IOException e) { 113 LOGGER.warn("IOException : ", e); 114 } 115 return rebuiltCss; //返回生成的css样式 116 } 117 118 /** 119 * 将xml解析出的css写入css_build.css 120 * 121 * @param generatedCss 122 */ 123 public void writeCssFile(String generatedCss, String currentTheme) { 124 String packageName = currentTheme.substring(0, 1).toLowerCase() + currentTheme.substring(1); 125 String url = SystemParameters.getCssPath() + "/" + packageName + "/CSS_Build.css"; 126 try { 127 File f = new File(url); 128 if (f.exists()) { 129 BufferedWriter output = new BufferedWriter(new FileWriter(f)); 130 f.setWritable(true); 131 output.write(generatedCss); 132 output.close(); 133 } else { 134 if (f.createNewFile()) { 135 f.setWritable(true); 136 BufferedWriter output = new BufferedWriter(new FileWriter(f)); 137 output.write(generatedCss); 138 output.close(); 139 } else { 140 LOGGER.info("Create Failed"); 141 } 142 } 143 } catch (Exception e) { 144 LOGGER.warn("Exception : ", e); 145 } 146 } 147 148 /** 149 * 通过获取不同主题的配色方案生成动态css 150 * 151 * @param elementNode 152 * @param configCss 153 * @return 154 */ 155 private StringBuffer switchValueByAttrId(Node elementNode, StringBuffer configCss) { 156 NamedNodeMap elementAttMap = elementNode.getAttributes(); 157 String attributeValue = elementAttMap.getNamedItem(CSS_CLASS_ID).getTextContent(); //获取CSS_CLASS_ID属性的值 158 String importantValue = ""; 159 String nodeTextContext = WRAPPER + elementNode.getTextContent() + " "; 160 if (elementAttMap.getNamedItem(IMPORTANT) != null) { 161 importantValue = "!important"; //获取important值 162 } 163 configCss.append(nodeTextContext + cssElementMap.get(attributeValue)); //cssElementMap函数调用attributeValue获取不同主题的颜色 164 configCss.append(importantValue); 165 configCss.append(";\n"); 166 return configCss; //返回获取主题颜色后的configCss 167 } 168 }
Java用DOM方法解析xml,布布扣,bubuko.com
原文:http://www.cnblogs.com/huijunhong00/p/java_dom_xml.html