您的位置:首页 > 编程语言 > Java开发

java操作xml w3c及xml存储图片文件

2012-06-08 15:05 501 查看
xml保存图片

package com.kelsen.beans.imagehelper;  
  
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.DataOutputStream;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
import sun.misc.BASE64Decoder;  
import sun.misc.BASE64Encoder;  
  
public class ImageToXML {  
  
  
/** 
* 把图片转成 BASE64Encoder  
* @param str_FileName 
* @return 
*/  
public static String readImage(String str_FileName) {  
   BufferedInputStream bis = null;  
   byte[] bytes = null;  
   try {  
    try {  
     bis = new BufferedInputStream(new FileInputStream(str_FileName));  
     bytes = new byte[bis.available()];  
     bis.read(bytes);  
    } finally {  
     bis.close();  
    }  
   } catch (FileNotFoundException e) {  
    e.printStackTrace();  
   } catch (IOException e) {  
    e.printStackTrace();  
   }  
   return new BASE64Encoder().encodeBuffer(bytes);  
}  
  
/** 
* 把BASE64Decoder转成图片 
* @param filename 
* @param content 
*/  
public static void saveImage(String filename, String content) {  
   try {  
    DataOutputStream dos = null;  
    try {  
     byte[] bs = new BASE64Decoder().decodeBuffer(content);  
     dos = new DataOutputStream(new BufferedOutputStream(  
       new FileOutputStream(filename)));  
     dos.write(bs);  
    } finally {  
     dos.close();  
    }  
   } catch (IOException e) {  
    e.printStackTrace();  
   }  
}  
  
}


解析xml

package com.kelsen.beans.xmlhelper;  
  
import java.io.File;  
import java.util.Vector;  
  
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.Document;  
import org.w3c.dom.Element;  
import org.w3c.dom.NamedNodeMap;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  
import org.w3c.dom.Text;  
  
public class KParseXML {  
  
/******************************** 
* 指定文件名,获取Document对象 
* @param str_FileName 
* @return 
********************************/  
public static Document createDocument(String str_FileName){  
   Document document_result=null;  
   try {  
    DocumentBuilderFactory documentBuilderFactory;  
    DocumentBuilder documentBuilder;  
    documentBuilderFactory=DocumentBuilderFactory.newInstance();  
    documentBuilder=documentBuilderFactory.newDocumentBuilder();  
    document_result=documentBuilder.parse(str_FileName);  
   } catch (Exception e) {  
    e.printStackTrace();  
   }  
   return document_result;  
}  
  
//////////////////////////////////////  
////节点、属性、值 查找部分  
//////////////////////////////////////  
  
/************************************* 
* 指定具体节点,获取标签体内容 
* @param doc 
* @param str_Label 
* @return 
*************************************/  
public static String getElementFirstChildValueByNodeName(Element element){  
   String str_result=null;  
   Text text = (Text) element.getFirstChild();  
   str_result=text.getNodeValue();  
   return str_result;  
}  
  
/************************************** 
* 指定节点名,从整个xml文件中找出所有此名的节点的集合 
* @param doc 
* @param str_Label 
* @param str_Attribute 
* @param str_Attribute_Value 
* @return 
***************************************/  
public static Vector getNodesByNodeName(Document doc,String str_NodeName){  
   Vector v_result=null;  
   NodeList nl = doc.getElementsByTagName(str_NodeName);   
   System.out.println("【提示】XML文档中有"+nl.getLength()+"个<"+str_NodeName+">标签");  
   int size=0;  
   Node tempnode;  
   if(nl != null){  
    size = nl.getLength();  
    v_result=new Vector();  
    for(int i=0; i<size; i++)  
    {  
     tempnode= nl.item(i);  
     v_result.add(tempnode);  
    }  
   }else{  
    return null;  
   }  
   return v_result;  
}  
  
  
/***************************************************** 
* 指定具体节点,指定此节点下的其他节点名,找出所有为其名的子节点 
* @param node 
* @param str_Label 
* @return Vector 的集合 
*****************************************************/  
public static Vector getNoesByNodeName(Node node,String str_NodeName){  
   Vector v_result=new Vector();  
   Node node_temp;  
   NodeList nodelist = node.getChildNodes();  
   for(int i=0;i<nodelist.getLength();i++){  
    node_temp=nodelist.item(i);  
    if(node_temp.getNodeName().equals(str_NodeName))  
     v_result.add(node_temp);  
   }  
   return v_result;  
}  
  
/************************************** 
* 匹配节点属性名及属性值去获取特定的节点 
* @param doc 
* @param str_Label 
* @param str_Attribute 
* @param str_Attribute_Value 
* @return 
***************************************/  
public static Node getNodeByAttributesValues(Document doc,String str_Label,String[] stra_Attributes,String[] stra_values){  
   Node node_result=null;  
   NodeList nl = doc.getElementsByTagName(str_Label);   
   System.out.println("【提示】xml文档中有"+nl.getLength()+"个<"+str_Label+">标签");  
   int size=0;  
   Node tempnode;  
   String []stra_att=new String[stra_Attributes.length];  
   if(nl != null)  
    size = nl.getLength();  
   for(int i=0; i<size; i++)  
   {  
    tempnode= nl.item(i);  
    int i_falg=0;  
    for(int j=0;j<stra_att.length;j++){  
     stra_att[j]=KParseXML.getAttrValue(tempnode,stra_Attributes[j]);  
     if(stra_att[j].equals(stra_values[j])){  
      i_falg++;  
     }  
    }  
    if(i_falg==stra_Attributes.length)  
    {  
      System.out.println("【提示】传递的要与指定的标签属性比较的参数都满足条件!");  
      node_result=tempnode;  
      break;  
    }else{  
     node_result=null;  
    }  
   }  
   return node_result;  
}  
  
  
/************************* 
* 获取某个节点某个属性的值 
* @param b 
* @param attrName 
* @return 
*************************/  
public static String getAttrValue(Node node,String str_AttrName)  
{  
   String str_result=null;   
   NamedNodeMap nnm = node.getAttributes();  
   if(nnm == null)  
    return null;  
   for(int i=0; i<nnm.getLength(); i++)  
   {  
    if(nnm.item(i).getNodeName().equals(str_AttrName))  
     str_result = nnm.item(i).getNodeValue();  
   }  
   return str_result;  
}  
  
  
///////////////////////////  
//修改部分  
//////////////////////////  
  
/********************************* 
* 指定节点,指定属性名,修改属性值 
* @param node 
* @param attrName 
* @param attrValue 
*********************************/  
public static void setAttrValue(Node node,String attrName,String attrValue){  
   NamedNodeMap attributes = node.getAttributes();  
   if(attributes !=null)  
   for(int i=0;i<attributes.getLength();i++){  
    String str_attributes_name = attributes.item(i).getNodeName();  
    if(str_attributes_name.equals(attrName))  
    attributes.item(i).setNodeValue(attrValue);  
   }  
}  
  
/****************************** 
* 指定具体标签,设置其标签体的值 
* @param element 
* @param str_value 
* @return 
******************************/  
public static boolean setElementValue(Element element,String str_value){  
   boolean b_result=true;  
   try{  
    Node text = element.getFirstChild();  
    text.setNodeValue(str_value);  
   }catch(Exception e){  
    b_result=false;  
    e.printStackTrace();  
   }  
   return b_result;  
}  
  
  
  
  
/////////////////////////////  
//文件处理部分  
////////////////////////////  
  
/********************************* 
* 在xml做好修改后,保存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, "GB2312");  
    DOMSource source = new DOMSource(document);  
    StreamResult result = new StreamResult(new File(filename));  
    transformer.transform(source, result);  
   } catch (Exception ex) {  
    flag = false;  
    ex.printStackTrace();  
   }  
   return flag;  
}  
  
}


测试类

//文件3

package com.kelsen.test;

import java.net.URL;
import java.util.Vector;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.kelsen.beans.imagehelper.ImageToXML;
import com.kelsen.beans.xmlhelper.KParseXML;

public class XMLTest {

public XMLTest(){
   //testSetElementValue();
   ImageToXMLTest();
   ImageToXMLReadImage();
}

/**
* 把图片文件转成BASE64Encoder存入xml文件中
*/
public void ImageToXMLTest(){
   URL url_FileName=this.getClass().getClassLoader().getResource("com/kelsen/files/image/kelsen.jpg");
   String str_FileName=url_FileName.getFile();
   String content = ImageToXML.readImage(str_FileName);
   testSetElementValue(content);
}

/**
* 从xml文件取得图片的BASE64Encoder内容从而创建本地图片文件
*/
public void ImageToXMLReadImage(){
   String str_context=readImage();
   ImageToXML.saveImage("D:/kkkk.jpg", str_context);
}

public String readImage(){
   URL url_FileName = this.getClass().getClassLoader().getResource("com/kelsen/files/xml/kelsen.xml");
   String str_FileName=url_FileName.getFile();
   Document document = KParseXML.createDocument(str_FileName);
   Vector nodes_get = KParseXML.getNodesByNodeName(document, "guilin");
   if(nodes_get!=null && nodes_get.size()>0){
    Element element=(Element) nodes_get.get(0);
    return KParseXML.getElementFirstChildValueByNodeName(element);
   }
   return null;
}

/**
* 标签体内容修改测试
*
*/
public void testSetElementValue(String str_context){
   URL url_FileName = this.getClass().getClassLoader().getResource("com/kelsen/files/xml/kelsen.xml");
   String str_FileName=url_FileName.getFile();
   Document document = KParseXML.createDocument(str_FileName);
   Vector nodes_get = KParseXML.getNodesByNodeName(document, "guilin");
   if(nodes_get!=null && nodes_get.size()>0){
    Element element=(Element) nodes_get.get(0);
    KParseXML.setElementValue(element,str_context);
   }
   KParseXML.doc2XmlFile(document, str_FileName);
   System.out.println("End 改完且保存结束!");
}

public static void main(String args[]){
   new XMLTest();
}
}


测试xml

<?xml version="1.0" encoding="GBK"?>  
<china name="中国">  
<guangdong name="广东省" description="省级标签">  
   <guangzhou>广州</guangzhou>  
   <shenzhen>深圳</shenzhen>  
   <shantou>汕头</shantou>  
</guangdong>  
<guangxi name="广西省" description="省级标签">  
   <guilin>桂林</guilin>  
</guangxi>  
<hunan name="湖南省" description="省级标签">  
   <changsha>长沙</changsha>  
   <zhuzhou>株洲</zhuzhou>  
</hunan>  
</china>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐