<domain>
<branch>
<key>variable</key>
<value>the value</value>
</branch>
</domain>
所依賴的jar包:
dom4j-1.6.1.jar和jaxen-1.1-beta-6.jar
如果不引入jaxen-1.1-beta-6.jar,在使用XPath獲取節點獲取時會引起下面的異常
Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/JaxenException
at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164)
...
xml配置文件
<!-- FTP目錄配置 caoxh 20101126 -->
<FtpPathConfig>
<!-- 工單根目錄 -->
<KeyValueMapping>
<Key>Root_cwmp</Key>
<Value>/opt/adsl/cwmp</Value>
</KeyValueMapping>
</FtpPathConfig>
代碼不解釋
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class FtpFileReader {
private static final String configFileName = "config.xml";
public static String getVariable8Map(String domain, String branch,
String variable) {
String retValue = "";
try {
Map keyValueMap = getKeyValueMap("//"+domain+"/"+branch);
if(keyValueMap!=null){
retValue = (String) keyValueMap.get(variable);
}
} catch (DocumentException e) {
e.printStackTrace();
}
return retValue;
}
public static Map getKeyValueMap(String xPath) throws DocumentException{
Map keyValueMap = new HashMap();
InputStream ins = FtpFileReader.class.getResourceAsStream("/"+ configFileName);
SAXReader reader = new SAXReader();
Document doc = reader.read(ins);
List list = doc.selectNodes(xPath);
for (Iterator it = list.iterator(); it.hasNext();) {
Node keyValueMappingConfig = (Node) it.next();
Node keyNode = keyValueMappingConfig.selectSingleNode("Key");
Node valueNode = keyValueMappingConfig.selectSingleNode("Value");
String key = keyNode.getText();
String value = valueNode.getText();
keyValueMap.put(key, value);
}
return keyValueMap;
}
public static void main(String[] args) {
String valule = getVariable8Map("FtpPathConfig","KeyValueMapping","Root_cwmp");
System.out.println("from config.xml:"+valule);
}
}