java xml 文件_Java 对xml文件的读写操作

/**

* 描述:数据库初始化基本类

*

* @作者 王群

* @创建日期 2010-04-08

* @修改人 xxx

* @修改日期 xxx

* @检查人 xxx

* @检查日期 xxx

*/

importjava.sql.SQLException;

importcom.ibatis.sqlmap.client.SqlMapClient;

importcom.oumasoft.bstmanage.ibatis.SqlMapConfig;

importcom.oumasoft.bstmanage.ibatis.data.JsgnPo;

importcom.oumasoft.bstmanage.ibatis.data.Test;

importjava.util.*;

importorg.w3c.dom.*;

importjava.io.*;

importjavax.servlet.http.HttpServletRequest;

importjavax.xml.transform.stream.*;

importorg.w3c.dom.*;

importjavax.xml.transform.*;

importjavax.xml.parsers.*;

importjavax.xml.transform.dom.*;

importorg.apache.log4j.Logger;

importcom.oumasoft.bstmanage.ibatis.dao.ClientDao;

publicclassInitDBDao{

staticLogger logger = Logger.getLogger(ClientDao.class.getName());

staticSqlMapClient sqlMap =null;

privatestaticFile file =null;//读写文件

privatestaticDocumentBuilderFactory factory =null;

privatestaticDocumentBuilder builder =null;

/**

* 将修改的内容添加到xml文件中

* @param document xml节点

* @param filename 文件路径

* @return 是否写入成功

*/

publicstaticbooleandoc2XmlFile(Document document, String filename) {

booleanflag =true;

try{

/** 将document中的内容写入文件中 */

TransformerFactory tFactory = TransformerFactory.newInstance();

Transformer transformer = tFactory.newTransformer();

/** 编码 */

//transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");

DOMSource source = newDOMSource(document);

//判断路径开头有没有“/”如果有则去掉

filename = "C".equals(filename.charAt(0)) ? filename : filename.substring(1);

StreamResult result = newStreamResult(newFileOutputStream(filename));

transformer.transform(source, result);

} catch(Exception ex) {

flag = false;

ex.printStackTrace();

}

returnflag;

}

/**

* 读取xml文件

* @param filename 文件路径

* @return 文件节点

*/

publicstaticDocument load(String filename) {

Document document = null;

try{

factory = DocumentBuilderFactory.newInstance();

builder = factory.newDocumentBuilder();

//判断路径开头有没有“/”如果有则去掉

filename = "C".equals(filename.charAt(0)) ? filename : filename.substring(1);

document = builder.parse(newFileInputStream(filename));

document.normalize();

} catch(Exception ex) {

ex.printStackTrace();

logger.error("找不到文件!");

}

returndocument;

}

/**

* 添加新的节点

* 根节点下没有节点的话直接添加

* 根节点下没有重名的直接添加

* 有重名的节点则更新节点属性

* @param filePath 文件路径

* @param nodeName 添加、更新的节点名

* @param attr 属性集合

* @return 是否成功

*/

publicstaticbooleanxmlAddDemoAttri(String filePath,String nodeName,Map attr) {

Document document = load(filePath);

Node root = document.getDocumentElement();

//创建节点元素,并命名

Element element =document.createElement(nodeName);

//向节点中添加属性

for(Object key : attr.keySet().toArray()) {

element.setAttribute(key.toString(), attr.get(key));

}

//找到根节点

NodeList nodeList = document.getElementsByTagName("Context");

//先判断根节点下有没有子节点,没有的话直接添加

Node rootNode = nodeList.item(0);

if(!root.hasChildNodes()){

nodeList.item(0).appendChild(element);

}else{

//如果有重复的节点,flag=true;

booleanflag =false;

NodeList rootChs = rootNode.getChildNodes();

//循环根节点下的所有子节点

for(inti =0; i 

Node node = rootChs.item(i);

//如果没有重名,并且是最后一个节点的就添加

if(!nodeName.equals(node.getNodeName()) && !flag && (i+1) == rootChs.getLength()){

nodeList.item(0).appendChild(element);

}elseif(nodeName.equals(node.getNodeName())){

//有重名的就看name属性,name一样就修改属性

if(node.hasAttributes()){

//如果有属性项,判断name属性值,如果name的值相同,则修改其他属性

if(null!= node.getAttributes().getNamedItem("name") && attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue())){

// 生成一个属性对象

Attr chAttr = null;

//向节点中添加属性

for(Object key : attr.keySet().toArray()) {

//不更新name属性

if(!"name".equals(key.toString())){

chAttr = document.createAttribute(key.toString());

chAttr.setValue(attr.get(key));

}

}

node.getAttributes().setNamedItem(chAttr);

}elseif(null!= node.getAttributes().getNamedItem("name") && !attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue()) && !flag && (i+1) == rootChs.getLength()){

//如果name的值不相同,且都没有相同的节点,添加新的节点

nodeList.item(0).appendChild(element);

}

}

}

}

}

// 将修改的内容添加到xml文件中

returndoc2XmlFile(document, filePath);

}

/**

* 查询xml文件中指定节点的制定属性值,对于重名的节点可以通过conditions属性进行筛选

* @param filePath xml文件路径

* @param nodeName 节点名

* @param conditions 条件属性,只有全部符合才会返回attr指定的属性的值

* @param attr 要查询的属性

* @return 查询的属性的值

*/

publicstaticString xmlReadDemoAttri(String filePath,String nodeName,Map conditions,String attr) {

String returnStr = null;

Document document = load(filePath);

Node root = document.getDocumentElement();

//找到根节点

NodeList nodeList = document.getElementsByTagName("Context");

//先找到context根节点

Node rootNode = nodeList.item(0);

if(!root.hasChildNodes()){

//没有子节点

}else{

NodeList rootChs = rootNode.getChildNodes();

//循环根节点下的所有子节点

for(inti =0; i 

Node node = rootChs.item(i);

//查找Resource连接节点

if(nodeName.equals(node.getNodeName())){

booleanisOk =false;

//对于有重名的节点,将节点的属性与条件比较

for(Object key : conditions.keySet().toArray()) {

String value = conditions.get(key);

String nodeValue = node.getAttributes().getNamedItem(key.toString()).getNodeValue();

//如果相同的属性,但是值不一样则退出循环

if(!value.equals(nodeValue)){

isOk = true;

break;

}

}

//节点中属性与条件属性一旦出现不一样这中断本次循环

if(isOk){

continue;

}else{

if(null!= node.getAttributes() &&null!= node.getAttributes().getNamedItem(attr)){

returnStr = node.getAttributes().getNamedItem(attr).getNodeValue();

}

}

}

}

}

returnreturnStr;

}

/**

* 对比xml文件中指定节点name属性值与指定值是否相等

* @param filePath xml文件路径

* @param nodeName 节点名

* @param nameValue 制定的name值

* @return boolean值,相同返回True

*/

publicstaticbooleanxmlReadDemoEqualsByName(String filePath,String nodeName,String nameValue) {

booleanreturnStr =false;

Document document = load(filePath);

Node root = document.getDocumentElement();

//找到根节点

NodeList nodeList = document.getElementsByTagName("Context");

//先找到context根节点

Node rootNode = nodeList.item(0);

if(!root.hasChildNodes()){

//没有子节点

returnfalse;

}else{

NodeList rootChs = rootNode.getChildNodes();

//循环根节点下的所有子节点

for(inti =0; i 

Node node = rootChs.item(i);

//查找Resource连接节点

if((nodeName.toLowerCase()).equals(node.getNodeName().toLowerCase())){

if(node.hasAttributes() &&null!= node.getAttributes().getNamedItem("name")){

String attrValue = node.getAttributes().getNamedItem("name").getNodeValue();

//如果name属性值相同,将标志设置为true

if(nameValue.equals(attrValue)){

returnStr = true;

}

}

}

}

}

returnreturnStr;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值