java 本身作的对XML文件的读写操做

XML文件实例:html

 

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Context>
 <WatchedResource>WEB-INF/web.xml</WatchedResource>

 <Resource auth="Container" maxActive="20" name="sss" password="123"
  type="javax.sql.DataSource" />
 <Resource auth="Container" maxActive="20" password="9003"
  type="javax.sql.DataSource" />
 <Resource as="nnnnnnnnnnnn" name="jdbc/sqlserver-database" />
</Context>

 

Java类:java

 

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.metadata.IIOMetadataNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.sun.org.apache.xerces.internal.dom.AttrNSImpl;
import com.sun.org.apache.xerces.internal.impl.xs.opti.DefaultNode;

public class T2 {

 /**
  * 将修改的内容添加到xml文件中
  * 
  * @param document
  * @param filename
  * @return
  */
 public static boolean doc2XmlFile(Document document, String filename) {
    boolean flag = true;
  try {
   /** 将document中的内容写入文件中 */
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer transformer = tFactory.newTransformer();
   /** 编码 */
   //transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");
   DOMSource source = new DOMSource(document);
   //判断路径开头有没有“/”若是有则去掉
   filename = "C".equals(filename.charAt(0)) ? filename : filename.substring(1);   
   StreamResult result = new StreamResult(new FileOutputStream(filename));
   transformer.transform(source, result);   
  } catch (Exception ex) {
   flag = false;
   ex.printStackTrace();
  }
  return flag;
 }

 /**
  * 读取xml文件
  * 
  * @param filename
  * @return
  */
 public static Document 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(new FileInputStream(filename)); 
   document.normalize();
  } catch (Exception ex) {
   ex.printStackTrace();
   logger.error("找不到文件!");
  }
  return document;
 }

 /**
  * 演示修改文件的具体某个节点的值
  */
 public static void xmlUpdateDemo() {
  Document document = load("c://Message.xml");
  Node root = document.getDocumentElement();
  /** 若是root有子元素 */
  if (root.hasChildNodes()) {
   /** ftpnodes */
   NodeList ftpnodes = root.getChildNodes();
   /** 循环取得ftp全部节点 */
   for (int i = 0; i < ftpnodes.getLength(); i++) {
    NodeList ftplist = ftpnodes.item(i).getChildNodes();
    for (int k = 0; k < ftplist.getLength(); k++) {
     Node subnode = ftplist.item(k);
     //修改节点的值
     if (subnode.getNodeType() == Node.ELEMENT_NODE
       && subnode.getNodeName() == "status") {
      subnode.getFirstChild().setNodeValue("1");
     }
    }

   }
  }

  doc2XmlFile(document, "c://Message.xml");
 }

 /**
  * 演示修改文件的具体某个节点的属性
  */
 public static void xmlUpdateDemoAttri() {
  Document document = load("c://xx.xml");
  Node root = document.getDocumentElement();
  /** 若是root有子元素 */
  if (root.hasChildNodes()) {
   
   
   
   /** ftpnodes 根节点的子节点 */
   NodeList ftpnodes = root.getChildNodes();
   /** 循环取得第一层子节点全部节点 */
   for (int i = 0; i < ftpnodes.getLength(); i++) {
    Node subnode = ftpnodes.item(i);
    //添加或修改某节点的属性配置
    if ("Resource".equals(subnode.getNodeName())) {
     // 生成一个属性对象
     Attr attr = document.createAttribute("ss");
     attr.setValue("ssss");
     subnode.getAttributes().setNamedItem(attr);
    }
   }
  }
  
  // 将修改的内容添加到xml文件中
  doc2XmlFile(document, "c://xx.xml");
 }
 
 /**添加新的节点
  * 根节点下没有节点的话直接添加
  * 根节点下没有重名的直接添加
  * 有重名的节点则更新节点属性
  * @param nodeName 添加、更新的节点名
  * @param attr 属性集合
  */
public static void xmlAddDemoAttri(String filePath,String nodeName,Map<String, String> 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;
   boolean flag = false;
   NodeList rootChs = rootNode.getChildNodes(); 
   //循环根节点下的全部子节点 
   for (int i = 0; i < rootChs.getLength(); i++) {
    Node node = rootChs.item(i);
    //若是没有重名,而且是最后一个节点的就添加
    if(!nodeName.equals(node.getNodeName()) && !flag && (i+1) == rootChs.getLength()){
     nodeList.item(0).appendChild(element);
    }else if(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);
      }else if(null != node.getAttributes().getNamedItem("name") && !attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue()) && !flag && (i+1) == rootChs.getLength()){
      //若是name的值不相同,且都没有相同的节点,添加新的节点
       System.out.println(attr.get("name"));
       System.out.println(node.getAttributes().getNamedItem("name").getNodeValue());
       nodeList.item(0).appendChild(element);
      }
     }
    }
   }
  }
  // 将修改的内容添加到xml文件中
  doc2XmlFile(document, filePath);
 }
 public static void main(String args[]) throws Exception {
  Map att = new HashMap<String, String>();
  att.put("as", "mmmmmmmmmmmmm");
  att.put("name", "jdbc/sqlserver-database");
  xmlAddDemoAttri("c://context.xml","Resource",att);
 }
}
相关文章
相关标签/搜索