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

来源:互联网 发布:凡科网站域名免费申请 编辑:程序博客网 时间:2024/06/02 06:31

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;  }    }  

测试类

//文件3package 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>  




原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 后颈部没有头发掉光了想植发怎么办 头发掉的厉害怎么办怎么拯救掉头发 头发可以种植吗 如果是秃顶怎么办 染头发把手指甲染黑了怎么办 怀孕两个月下体流褐色分泌物怎么办 头发总是大把大把的得掉 怎么办 严重脱发怎么办去问南宁肤康 脱发严重怎么办去看南宁肤康 前额头发少怎么办 如何使头发增多 生完宝宝头发一把一把的掉怎么办 生完宝宝后头发掉的厉害怎么办 生完宝宝头发掉的厉害怎么办 生了小孩后头发掉很多怎么办 生了孩子头发掉的很厉害怎么办 母乳期头发掉的很厉害怎么办 宝宝吃母乳头发掉的厉害怎么办 头发油腻头皮屑多还掉头发怎么办 头发剪了中分刘海弯了怎么办 头发掉了长出来的头发很细怎么办? 头皮损伤毛囊怎么办还会长头发吗 一岁宝宝头发稀少怎么办能刮光头么 前编头发长了怎么办怎么梳理 九个月宝宝头发稀少不长怎么办 前牙吃饭咬合很深吃饭就痛怎么办 吃了甜的冷的就牙疼怎么办 吃热的凉的甜的牙疼怎么办 头发太细了想让头发变粗点怎么办 我的头发又少又很油该怎么办 头发油掉发头顶头发稀疏怎么办 我的头发天生就少又细怎么办 头发越来越少怎么办 用什么好呢 头发油掉头发怎么办吃什么药好 生完孩子三个月掉头发很厉害怎么办 电夹板夹头发现在掉头发怎么办 刚剪完的头发前面短后面长怎么办 头发太多太厚怎么办_百度经验 米诺地尔搽剂喷在头皮上痛怎么办 米诺地尔擦了头皮痒怎么办 头发又细又少一天不洗就油怎么办 头又尖头发又细又少不知怎么办 蘑菇头发型留长尴尬期怎么办