zoukankan      html  css  js  c++  java
  • dom paser

    dom paser

    /**
     * 
     */
    package ec.utils;
    
    import java.io.BufferedInputStream;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import ec.application.ECSigleton;
    import ec.domain.common.conversion.ConvType.Namespace;
    import ec.export.XMLHelper;
    import ec.product.ECItem;
    
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Result;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.TransformerException;
    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.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    
    /**
     * @author yangff
     *
     */
    public class ShowDBMwithRT {
    
        public static ShowDBMwithRT instance;
        public ShowDBMwithRT getInstance()
        {
            if(instance==null)
            {
                instance=new ShowDBMwithRT();
            }
            return instance;
        } 
        
        //add "DBM" before "RT"
        public String addDBMbeforeRT(String passstr)
        {
            //Air Handler-RT 18 MF</model>
            String strdbm=passstr;//RoofTop-RT 18 MF
            
            String strfront="";
            String strafter="";
            
            strfront=strdbm.substring(0, strdbm.indexOf("-")); //Air Handler-
            strafter="-DBM "+strdbm.substring(strdbm.indexOf("-")+1);
            
            strdbm=strfront+strafter;
            return strdbm;
        }
        
        
         /*
        <field>
        <name>Model #</name>
        <value>RT 18 MF</value>
        <type>Dotted</type>
        </field>
    
         <model>Air Handler-RT 18 MF</model>
         
         
         <field>
        <name>Air handler model</name>
        <value>RT 18 MF</value>
        <type>Dotted</type>
        </field>
    
        <description>RT 18 MF</description>
        */
        //process xml for preprint
        public Document processXmlforprint(String passxmlstr)
        {
             Document xmlDoc=null;
             
             try {
                    ByteArrayInputStream bis = new ByteArrayInputStream(passxmlstr.getBytes("UTF-8"));
                    xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bis);
                } catch (Throwable e) {
                    try {
                        throw new Exception("MSG_COULDN'T_PARSE_XML", e);
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                
                NodeList nlds=xmlDoc.getElementsByTagName("description");
                showElem(nlds);
                nlds=xmlDoc.getElementsByTagName("value");
                showElem(nlds);
                nlds=xmlDoc.getElementsByTagName("model");
                showElem(nlds);
                
               
             return xmlDoc;
            
        
        }
        
        public static void showElem(NodeList nl){
            
            for(int i=0;i<nl.getLength();i++){
                
                Node n=nl.item(i);
                if(n.hasChildNodes()){
                  //  System.out.print("<"+n.getNodeName()+">");
                    //递归
                    showElem(n.getChildNodes());
                  //  System.out.print("</"+n.getNodeName()+">");
                }else{
                     
                    //判断是不是文本
                    if(n.getNodeType()==Node.TEXT_NODE){
                         
                        if(n.getNodeValue().indexOf("RT")!=-1)
                         {
                             
                             if(n.getNodeValue().startsWith("Air Handler-RT"))
                             {
                                 //<model>Air Handler-RT 18 MF</model>
                                 String strmodel=n.getNodeValue();
                                 String strfront="";
                                String strafter="";
                                
                                strfront=strmodel.substring(0, strmodel.indexOf("-")); //Air Handler-
                                strafter="-DBM "+strmodel.substring(strmodel.indexOf("-")+1);
                                
                                strmodel=strfront+strafter;
                                 
                                 n.setNodeValue(strmodel);
                                 
                             }
                             else
                             {
                                 n.setNodeValue("DBM "+n.getNodeValue());
                             }
                             
                             break;
                         }
                        
                        //System.out.print(n.getNodeValue());
                        
                    }else{
                       // System.out.print("<"+n.getNodeName()+">");
                        //System.out.print("</"+n.getNodeName()+">");
                    }
                    break;
                }
            }
        }
        
        
        
        /*
        <field>
        <name>Compressors (Qty)</name>
        <value>5SH240_4(4)</value>
        <type>Dotted</type>
        </field>
        */
        //ACDS COMPRESS CHANGE
        public Document processXmlforprintBeta(String passxmlstr)
        {
             Document xmlDoc=null;
             
             try {
                    ByteArrayInputStream bis = new ByteArrayInputStream(passxmlstr.getBytes("UTF-8"));
                    xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bis);
                } catch (Throwable e) {
                    try {
                        throw new Exception("MSG_COULDN'T_PARSE_XML", e);
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                
                NodeList nlds=xmlDoc.getElementsByTagName("value");
                showElem_ACDS(nlds);
               
             return xmlDoc;
            
        
        }
        
        
    public void showElem_ACDS(NodeList nl){
            
            for(int i=0;i<nl.getLength();i++){
                
                Node n=nl.item(i);
                if(n.hasChildNodes()){
                  //  System.out.print("<"+n.getNodeName()+">");
                    //递归
                    showElem_ACDS(n.getChildNodes());
                  //  System.out.print("</"+n.getNodeName()+">");
                }else{
                     
                    //判断是不是文本
                    if(n.getNodeType()==Node.TEXT_NODE){
                         
                        if((n.getNodeValue().indexOf("SH")!=-1 || n.getNodeValue().indexOf("HLJ")!=-1)&& n.getNodeValue().contains("_") && n.getNodeValue().contains("(") && n.getNodeValue().contains(")")){
                            
                            String strmodel=n.getNodeValue();
                            if(strmodel.contains("5SH"))
                            {
                                strmodel=strmodel.replaceAll("5SH", "SH");                 
                            } 
                            
                            if(strmodel.contains("SH300"))
                            {
                                strmodel=strmodel.replaceAll("SH300", "SH295");                 
                            } 
                            if(strmodel.contains("/")){
                                
                                String a=strmodel.substring(0,strmodel.indexOf("_"));
                                String b=strmodel.substring(strmodel.indexOf("("),strmodel.indexOf("/"));
                                String c=strmodel.substring(strmodel.indexOf("/"),strmodel.lastIndexOf("_"));
                                String d=strmodel.substring(strmodel.lastIndexOf("("),strmodel.lastIndexOf(")")+1);
                                strmodel= a+b+c+d;
                                
                            }else{
                                String a=strmodel.substring(0,strmodel.indexOf("_"));
                                String b=strmodel.substring(strmodel.indexOf("("));
                                
                                strmodel= a+b;
                            }
                            
                            n.setNodeValue(strmodel);
                            break;
                        }
                        //System.out.print(n.getNodeValue());
                        
                    }else{
                       // System.out.print("<"+n.getNodeName()+">");
                        //System.out.print("</"+n.getNodeName()+">");
                    }
                    break;
                }
            }
        }
        // FOR AVX 
    public Document processXmlforprintAVX(String passxmlstr)
    {
         Document xmlDoc=null;
         
         try {
                ByteArrayInputStream bis = new ByteArrayInputStream(passxmlstr.getBytes("UTF-8"));
                xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bis);
            } catch (Throwable e) {
                try {
                    throw new Exception("MSG_COULDN'T_PARSE_XML", e);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            
            NodeList nlds=xmlDoc.getElementsByTagName("value");
            showElem_AVX(nlds);
           
         return xmlDoc;
        
    
    }
    
    
    public void showElem_AVX(NodeList nl){
        
        for(int i=0;i<nl.getLength();i++){
            
            Node n=nl.item(i);
            if(n.hasChildNodes()){
              //  System.out.print("<"+n.getNodeName()+">");
                //递归
                showElem_AVX(n.getChildNodes());
              //  System.out.print("</"+n.getNodeName()+">");
            }else{
                 
                //判断是不是文本
                if(n.getNodeType()==Node.TEXT_NODE){                 
                 
                        String strmodel=n.getNodeValue();               
                        //System.out.println("********"+strmodel);
                        if(strmodel.contains("cm"))
                        {
                            strmodel=strmodel.replaceAll("cm", "MSC");  
                            n.setNodeValue(strmodel);
                            break;
                        } 
                    
                }else{
                   // System.out.print("<"+n.getNodeName()+">");
                    //System.out.print("</"+n.getNodeName()+">");
                }
                break;
            }
        }
    }
    
    
    
    
    
        public static Namespace getNamespaceFromMap(String name) 
        {
            Namespace name_str= null;
            Iterator<String> it=ECItem.mFamate.keySet().iterator();
             while(it.hasNext())
             {
                 String tmp= it.next().toString();
                 if(tmp.toUpperCase().indexOf(name.toUpperCase())!=-1)
                 {
                     name_str=(Namespace) ECItem.mFamate.get(tmp);
                     break;
                 }
             }
             return name_str;
        }
        //==========================================xml=======common method [1]=====================================    
            /**
             * common method "getfromXml " get target from Xml
             * 
             * @param args example:
             * 
             * {
             * <version>SPEC ver. 7.0, 26469</version>
             * String discription:version
             * String strfind :"SPEC ver"
             * return "SPEC ver. 7.0, 26469"
             *  }
             *  
             */
            
            static String targetstr="";
            
            public static String  getfromXml(String passxmlstr,String discription,String strfind)
            {     String result="";
                 Document xmlDoc=null;
                 
                 try {
                        ByteArrayInputStream bis = new ByteArrayInputStream(passxmlstr.getBytes("UTF-8"));
                        xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bis);
                    } catch (Throwable e) {
                        try {
                            throw new Exception("MSG_COULDN'T_PARSE_XML", e);
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                    
                    NodeList nlds=xmlDoc.getElementsByTagName(discription);
                   
                    result=showElem_target(nlds,strfind);
                 return result;
            }
            
            
        public static String showElem_target(NodeList nl,String strfind){
            boolean flag=false;
                for(int i=0;i<nl.getLength();i++){
                    
                    Node n=nl.item(i);
                    if(n.hasChildNodes()&&!flag){
                      //  System.out.print("<"+n.getNodeName()+">");
                     
                        showElem_target(n.getChildNodes(),strfind);
                      //  System.out.print("</"+n.getNodeName()+">");
                    }else{
                       
                        if(n.getNodeType()==Node.TEXT_NODE){
                            //System.out.print(n.getNodeValue());
                            if(n.getNodeValue().indexOf(strfind)!=-1){
                                targetstr=n.getNodeValue();
                                flag=true;
                                 break; 
                            }
                            
                        }else{
                           // System.out.print("<"+n.getNodeName()+">");
                            //System.out.print("</"+n.getNodeName()+">");
                        }
                        break;
                    }
                }
                return targetstr;
            }
        //==========================================xml=======common method [1]=====================================    
    
    
        //==========================================xml=======common method [2]=====================================
    
         
        /**
         * common method "findbynode" get target from Xml 2
         * 
         * @param args example:
         * 
         * {
         * <field>     //field-->bignode
         *    <name>Motor hand</name> //name-->clum1 , "Motor hand"-->itemvalue
         *    <value>Right</value>    //value-->clum2
         *    <type>Dotted</type>
         * </field>
         *  }
         *  
         */
        public static ArrayList  findbynode(String passxmlstr,String bignode,String clum1,String itemvalue,String clum2)
        {  
             
            ArrayList<String> result=new ArrayList<String>();
            /*
            bignode="field";
            clum1="name";
            clum2="value";
            */
            
            ArrayList<Map> al=paserxmlbynode(passxmlstr,bignode);
            for(Map m : al)
            { 
                 if(m.containsKey(clum1)&&m.get(clum1).toString().equals(itemvalue))
                 {
                     result.add(m.get(clum2).toString());
                     //break;
                 }
            }
             
            //System.out.println(result);
            return result;
        }
    
        public static ArrayList paserxmlbynode(String passxmlstr,String bignode)
        {
             Document xmlDoc=null;
             
             try {
                    ByteArrayInputStream bis = new ByteArrayInputStream(passxmlstr.getBytes("UTF-8"));
                    xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bis);
                } catch (Throwable e) {
                    try {
                        throw new Exception("MSG_COULDN'T_PARSE_XML", e);
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                
                 //   System.out.print(passxmlstr);
                ArrayList<Map> listitem=new ArrayList<Map>();   
                
                // find bignode
                NodeList nlds=xmlDoc.getElementsByTagName(bignode);
                int size =nlds.getLength();
                for(int j=0;j<size;j++)
                {
                    Node nd=nlds.item(j).getFirstChild().getNextSibling();
                    Map<String,String> map=new HashMap<String,String>();
                    while(nd!=null)
                    {
                        map.put(nd.getNodeName(), nd.getFirstChild().getNodeValue());
                        nd= nd.getNextSibling().getNextSibling();
                    }
                    listitem.add(map);
                }
              
               // System.out.print(listitem.size());
             return listitem;
        }
        public static ArrayList  findbynode(Document xmlDoc,String bignode,String clum1,String itemvalue,String clum2)
        {  
             
            ArrayList<String> result=new ArrayList<String>();
            /*
            bignode="field";
            clum1="name";
            clum2="value";
            */
            
            ArrayList<Map> al=paserxmlbynode(xmlDoc,bignode);
            for(Map m : al)
            { 
                 if(m.containsKey(clum1)&&m.get(clum1).toString().equals(itemvalue))
                 {
                     result.add(m.get(clum2).toString());
                     //break;
                 }
            }
             
            //System.out.println(result);
            return result;
        }
        public static ArrayList paserxmlbynode(Document xmlDoc,String bignode)
        {
                 //   System.out.print(passxmlstr);
                ArrayList<Map> listitem=new ArrayList<Map>();   
                
                // find bignode
                NodeList nlds=xmlDoc.getElementsByTagName(bignode);
                int size =nlds.getLength();
                for(int j=0;j<size;j++)
                {
                    Node nd=nlds.item(j).getFirstChild().getNextSibling();
                    Map<String,String> map=new HashMap<String,String>();
                    while(nd!=null)
                    {
                        map.put(nd.getNodeName(), nd.getFirstChild().getNodeValue());
                        nd= nd.getNextSibling().getNextSibling();
                    }
                    listitem.add(map);
                }
              
               // System.out.print(listitem.size());
             return listitem;
        }  
        //=========================================common method=============================================
            /* 
             * return  description content "1 Access panel(s) standard"
            
             <price description="1 Access panel(s) standard"
              list="0.0" markupType="0" metric="uEnglish"
              net="0.0" shipLoose="false"
             />
            */
             public static List<String> testfindnodebyattr(String passxmlstr,String node,String strAttr) {
         
            
                     /*
                     String path="D:\Task\filter-init\filter.xml";
                     BufferedReader bufReader=null;
                     String passxmlstr="";
                     String temps="";
                     
                            try {
                                bufReader = new BufferedReader(new FileReader(path));
                                while((temps=bufReader.readLine())!=null){
                                    passxmlstr+=temps;
                                }
                                
                            } catch (FileNotFoundException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                     finally{
                         try {
                            bufReader.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                     }
                     */
                     String result="";
                     Document xmlDoc=null;
                     
                     try {
                            ByteArrayInputStream bis = new ByteArrayInputStream(passxmlstr.getBytes("UTF-8"));
                            xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bis);
                        } catch (Throwable e) {
                            try {
                                throw new Exception("MSG_COULDN'T_PARSE_XML", e);
                            } catch (Exception e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                        }
                        
                        NodeList nlds=xmlDoc.getElementsByTagName(node);
                        
                     return  showAttr_target(nlds,strAttr);
           }
    
            //=========================================common method=============================================
            public static List showAttr_target(NodeList nl,String strAttr)
            {
                List l=new ArrayList();
                 String targetstr="";
                 for(int i=0;i<nl.getLength();i++)
                 {
                    Node n=nl.item(i);
                    targetstr=n.getAttributes().getNamedItem(strAttr).toString();
                    l.add(targetstr);
                 } 
                 return l;
            }
            // =========================================common method=============================================
    
        
            public static String changeCompName(String compName){
                String NewCompName="";
                
                //cm1230NHL6X7K(2)
                //String tests="cm1230NHL6X7K(2)";
                //compName=tests;
                
                boolean twice=false;
                if(compName.indexOf("(")>=0) twice=true;
                Pattern p=Pattern.compile("([a-z]+)(\d+)");
                Matcher m=p.matcher(compName);
                while(m.find()) {
                    NewCompName=m.group();
                }
     
                if(twice){
                    Pattern p2=Pattern.compile("(?<=\()[^\)]+");
                    Matcher m2=p2.matcher(compName);
                    while(m2.find()) {
                        NewCompName+="("+m2.group()+")";
                    }
                }
                if(NewCompName.indexOf("cm")>=0)
                {
                    NewCompName=NewCompName.replaceAll("cm", "MSC");
                } 
                //System.out.println(NewCompName);
                return NewCompName;
            }
            
            
            
        public static void main(String[] args) 
        {
            
            ShowDBMwithRT sdrt=new ShowDBMwithRT();  
            //sdrt.getInstance().processXmlforprint("");
            sdrt.getInstance().changeCompName("");
        }
        
         
         
    
    }
  • 相关阅读:
    超详细JSON解析步骤
    HTTP请求头和响应头总结
    Oracle 数据库常用操作语句大全
    关于HTTP协议,一篇就够了
    PowerDesigner工具建表步骤
    求助:ACM剑气算法
    一道题
    个人Java学习中的遇到的几个模糊的地方
    Java编程:数学黑洞6174
    高级查询
  • 原文地址:https://www.cnblogs.com/rojas/p/5318243.html
Copyright © 2011-2022 走看看