zoukankan      html  css  js  c++  java
  • dom4j_01_02

      1 package xml_z;
      2 
      3 import java.io.ByteArrayOutputStream;
      4 import java.io.File;
      5 import java.io.FileInputStream;
      6 import java.io.FileOutputStream;
      7 import java.io.InputStream;
      8 import java.io.OutputStreamWriter;
      9 import java.util.HashMap;
     10 import java.util.List;
     11 
     12 import org.dom4j.Document;
     13 import org.dom4j.DocumentFactory;
     14 import org.dom4j.Element;
     15 import org.dom4j.io.OutputFormat;
     16 import org.dom4j.io.SAXReader;
     17 import org.dom4j.io.XMLWriter;
     18 
     19 public class Tdom4jTest
     20 {
     21 // dom4j 的两个 jar文件
     22 //    (1)、dom4j-1.6.1.jar
     23 //    (2)、jaxen-1.1-beta-6.jar ==> 这个是用于支持xpath的
     24     
     25 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
     26 //    打开XML文件
     27     
     28     // 打开XML文件 (带 命名空间)
     29     public static Document DocumentGet_byXmlFile_ns(String _strFullFileName, String[] _strsNsHashKey, String[] _strsNsHashValue) throws Exception
     30     {
     31         if ((_strsNsHashKey == null) || (_strsNsHashValue == null))
     32             return null;
     33         if (_strsNsHashKey.length != _strsNsHashValue.length)
     34             return null;
     35         if ((_strsNsHashKey.length == 0) || (_strsNsHashValue.length == 0))
     36             return null;
     37         
     38         // 这里是新建的 DocumentFactory实例,如果不传参数的话,使用的就是单例的DocumentFactory对象
     39         SAXReader reader = new SAXReader(new DocumentFactory());
     40 
     41         HashMap<String, String> hmNS = new HashMap<String, String>();
     42         for (int i=0; i<_strsNsHashKey.length; i++)
     43             hmNS.put(_strsNsHashKey[i], _strsNsHashValue[i]);
     44         
     45         // 设置 命名空间
     46         reader.getDocumentFactory().setXPathNamespaceURIs(hmNS);
     47         File file = new File(_strFullFileName);
     48         //return reader.read(_strFullFileName);// 直接传文件名时,会有乱码...
     49         return reader.read(file);
     50     }
     51     
     52     // 打开XML文件 (不带 命名空间)
     53     public static Document DocumentGet_byXmlFile(String _strFullFileName) throws Exception
     54     {
     55         // 通过 单例的DocumentFactory对象 来加载XML文件
     56         SAXReader sr = new SAXReader();
     57         //Document doc = sr.read(_strFullFileName);
     58         //return doc;
     59         File file = new File(_strFullFileName);
     60         return sr.read(file);
     61     }
     62     
     63     // 通过流 加载XML (这里是通过 文件流,我想 通过字符流应该也是可以的)
     64     public static Document DocumentGet_byXmlStream(String _strFullFileName) throws Exception
     65     {
     66         // 打开文件流    
     67         File file = new File(_strFullFileName);
     68         if (! file.exists()) 
     69         {
     70             System.out.println("File not find : "+file.getName());
     71             return null;
     72         }
     73     
     74         InputStream in = new FileInputStream(file);
     75         
     76         // Dom4j 读文件
     77         SAXReader reader = new SAXReader();
     78         return reader.read(in);
     79     }
     80     
     81 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
     82 //    基本节点操作
     83     
     84     // 得到 root Element
     85     public static Element RootGet(Document _doc)
     86     {
     87         return _doc.getRootElement();
     88     }
     89     
     90     // 添加Element
     91     public static Element ElementNew(Element _eleParent, String _strEleName)
     92     {
     93         return _eleParent.addElement(_strEleName);
     94     }
     95     
     96     // 添加/设置 属性
     97     public static void AttributeSet(Element _ele, String _strAttrName, String _strAttrValue)
     98     {
     99         _ele.addAttribute(_strAttrName, _strAttrValue);
    100     }
    101     
    102     // 获取属性的值
    103     public static String AttributeGet(Element _ele, String _strAttrName, String _strDefaultAttrValue)
    104     {
    105         if (_strDefaultAttrValue == null)
    106             return _ele.attributeValue(_strAttrName);
    107         else
    108             return _ele.attributeValue(_strAttrName, _strDefaultAttrValue);
    109     }
    110     
    111     // 获取节点的 TagName
    112     public static String TagNameGet(Element _ele)
    113     {
    114         return _ele.getName();
    115     }
    116 
    117 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    118 //    得到节点的XML文本
    119     
    120     // 得到某个Element的XML字符 (易读格式)
    121     // 参数2: 返回的字符的编码格式
    122     public static String ElementXml(Element _ele, String _strCharsetName) throws Exception
    123     {
    124         OutputFormat of = OutputFormat.createPrettyPrint();
    125         
    126         ByteArrayOutputStream bos = new ByteArrayOutputStream();
    127         OutputStreamWriter osw = null;
    128         if (_strCharsetName == null)
    129             osw = new OutputStreamWriter(bos);
    130         else
    131             osw = new OutputStreamWriter(bos, _strCharsetName);
    132         XMLWriter writer = new XMLWriter(osw, of);
    133         
    134         writer.write( _ele );
    135         writer.close();
    136         
    137         // ***
    138         
    139         String strRtn = new String(bos.toByteArray());
    140 //System.out.println(strRtn);
    141         return strRtn;
    142     }
    143     
    144     // 得到某个Element的XML字符 (不易读,一整行字符串 的形式)
    145     // 参数2: 返回的字符的编码格式
    146     public static String ElementXml_Compact(Element _ele, String _strCharsetName) throws Exception
    147     {
    148         OutputFormat of = OutputFormat.createCompactFormat();
    149         
    150         ByteArrayOutputStream bos = new ByteArrayOutputStream();
    151         OutputStreamWriter osw = null;
    152         if (_strCharsetName == null)
    153             osw = new OutputStreamWriter(bos);
    154         else
    155             osw = new OutputStreamWriter(bos, _strCharsetName);
    156         XMLWriter writer = new XMLWriter(osw, of);
    157         
    158         writer.write( _ele );
    159         writer.close();
    160         
    161         // ***
    162         
    163         String strRtn = new String(bos.toByteArray());
    164 //System.out.println(strRtn);
    165         return strRtn;
    166     }
    167     
    168 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    169 //    保存文件
    170     
    171     // 通过Document 来保存XML文件
    172     public static void Save_byDoc(Document _doc, String _strFullFileName, boolean _bEscapeText) throws Exception
    173     {
    174         OutputFormat of = OutputFormat.createPrettyPrint();
    175         of.setEncoding("utf-8");
    176         //of.setTrimText(false);
    177         //of.setLineSeparator("
    ");
    178 
    179         FileOutputStream fos = new FileOutputStream( _strFullFileName );
    180         OutputStreamWriter osw = new java.io.OutputStreamWriter(fos, "utf-8");
    181         XMLWriter writer = new XMLWriter(osw, of);
    182         writer.setEscapeText(_bEscapeText); // 转义符 // 是否对特殊符号转义
    183         writer.write( _doc );
    184         writer.close();
    185     }
    186     
    187     // 通过Document 来保存XML文件 (并且去掉里面的 命名空间 字符串)
    188     public static String Save_byDoc_noNS(Document _doc, String _strFullFileName, String _strNsName, String _strNsValue) throws Exception
    189     {
    190         OutputFormat of = OutputFormat.createPrettyPrint();
    191         
    192         ByteArrayOutputStream bos = new ByteArrayOutputStream();
    193         OutputStreamWriter osw = new OutputStreamWriter(bos);
    194         XMLWriter writer = new XMLWriter(osw, of);
    195         
    196         writer.write( _doc );
    197         writer.close();
    198         
    199         // ***
    200         
    201         String strRtn = new String(bos.toByteArray());
    202         //String strRegex = " xmlns.*?""+_strNsHashValue+""";
    203         String strRegex = " "+_strNsName+".*?""+_strNsValue+""";
    204         strRtn = strRtn.replaceAll(strRegex, ""); // 去掉命名空间
    205         //strRtn = strRtn.replaceAll("	+", "	"); // 少一点"	"
    206         System.out.println(strRtn);
    207 //            strRtn = new String(strRtn.getBytes(), "utf-8");
    208 //            System.out.println(strRtn);
    209         // *** *** ***
    210 
    211         of.setEncoding("utf-8");
    212         of.setTrimText(false);
    213         
    214         FileOutputStream fos = new FileOutputStream( _strFullFileName );
    215         osw = new java.io.OutputStreamWriter(fos, "utf-8");
    216         writer = new XMLWriter(osw);
    217         writer.setEscapeText(false);
    218         writer.write( strRtn );
    219         writer.close();
    220         
    221         return null;
    222     }
    223     
    224 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    225 //    查找  Element
    226     
    227     // 查找 单个 Element
    228     public static Element ElementGet(Document _doc, String _strXpath)
    229     {
    230         //Element ele = (Element)_doc.selectSingleNode("//cge:PSR_Ref");
    231         Element ele = (Element)_doc.selectSingleNode(_strXpath);
    232         if (ele == null)
    233             System.out.println("ElementGet ==> 'ele == null'");
    234         
    235         return ele;
    236     }
    237     
    238     public static List<?> ElementsGet(Document _doc, String _strXpath)
    239     {
    240         return _doc.selectNodes(_strXpath);
    241     }
    242 
    243 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    244 //    节点中 添加 字符串
    245     
    246     // 往节点里面添加 字符串 (用的是 "Element = Element.addEntity(String name, String text);")
    247     public static void ElementAddText(Element _ele, String _strEntityName, String _strEntityText)
    248     {
    249         _ele.addEntity(_strEntityName, _strEntityText);
    250     }
    251     
    252 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    253 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    254     
    255     public static void main(String[] args) throws Exception
    256     {
    257         /*
    258         String strFullFIleName = "F:\ZC_Code_E\workspace__MyEclipse2013\dom4j_test\FZX069A开关站图_V1.svg";
    259         String strFullFIleName1 = "F:\ZC_Code_E\workspace__MyEclipse2013\dom4j_test\FZX069A开关站图_V1__Z.svg";
    260         
    261         Document doc = Tdom4jTest.DocumentGet_byXmlFile(strFullFIleName);
    262         Tdom4jTest.Save_byDoc(doc, strFullFIleName1, false);
    263         */
    264         
    265         String strFullFIleName = "F:\ZC_Code_E\workspace__MyEclipse2013\dom4j_test\FZX069A开关站图_V1.svg";
    266         
    267         String[] strNsNames = {
    268                 "xmlns",    // 根 ns
    269                 "xlink",    // 子 ns
    270                 "cge",        // 子 ns
    271                 "hzsvg"};    // 子 ns
    272         String[] strNsValues= {
    273                 "http://www.w3.org/2000/svg",
    274                 "http://www.w3.org/1999/xlink",
    275                 "http://iec.ch/TC57/2005/SVG-schema#",
    276                 "http://holleygrid.cn/svg"};
    277         Document doc = Tdom4jTest.DocumentGet_byXmlFile_ns(strFullFIleName, strNsNames, strNsValues);
    278         Element ele = Tdom4jTest.ElementGet(doc, "//xmlns:g[@id='1650207777209']");
    279         // 下面这样,找不到节点
    280         //Element ele = Tdom4jTest.ElementGet(doc, "//g[@id='1650207777209']");
    281         if (ele == null)
    282             System.out.println("//xmlns:g[@id='1650207777209'] ==> find nothing");
    283         else
    284             System.out.println(Tdom4jTest.TagNameGet(ele));
    285         
    286         ele = Tdom4jTest.ElementGet(doc, "//cge:PSR_Ref");
    287         if (ele == null)
    288             System.out.println("//cge:PSR_Ref ==> find nothing");
    289         else
    290             System.out.println(ele.attributeValue("ObjectID"));
    291         
    292         List<?> list = Tdom4jTest.ElementsGet(doc, "//cge:PSR_Ref");
    293         if (list != null)
    294             for (int i=0; i<list.size(); i++)
    295             {
    296                 Element e = (Element) list.get(i);
    297                 System.out.println(e.attributeValue("ObjectID"));
    298             }
    299     }
    300 
    301 }

    测试代码保存于:百度云 CodeSkill33 --> 全部文件 > java_测试_code_zc --> dom4j_test__Work_20151207_1551.rar

    C

  • 相关阅读:
    [原创]如何在Windows下安装Bugfree2.0.0.1
    [原创]网站性能优化利器之一"google page speed"
    [原创]下一代Web 应用程序安全性测试工具HP WebInspect简介
    [原创]微软软件项目管理Team Foundation Server之测试人员
    [原创]Yeepay网站安全测试漏洞之跨站脚本注入
    [原创]软件测试过程改进的内容和注意事项
    [原创]快钱99bill网站安全性测试漏洞之“跨站式脚本注入”
    马化腾内部讲座:让产品自己召唤人
    [转贴]可用性测试
    [原创]浅谈缺陷分析的意义和方法
  • 原文地址:https://www.cnblogs.com/codeskilla/p/5026295.html
Copyright © 2011-2022 走看看