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(, strdbm.indexOf("-")); //Air Handler-
strafter="-DBM "+strdbm.substring(strdbm.indexOf("-")+); 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=;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")!=-)
{ 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(, strmodel.indexOf("-")); //Air Handler-
strafter="-DBM "+strmodel.substring(strmodel.indexOf("-")+); 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=;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")!=- || n.getNodeValue().indexOf("HLJ")!=-)&& 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(,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(")")+);
strmodel= a+b+c+d; }else{
String a=strmodel.substring(,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=;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())!=-)
{
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=;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)!=-){
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=;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=;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=;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("(")>=) 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")>=)
{
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("");
} }

dom paser的更多相关文章

  1. Java sax、dom、pull解析xml

    -------------------------------------SAX解析xml---------------------------------- >Sax定义 SAX是一个解析速度 ...

  2. 解析XML的几种方式:DOM、SAX、PULL

    DOM解析 解析器读入整个文档,然后构建一个主流内存的树结构,然后代码就可以使用dom接口来操作这个树结构. 优点: 整个文档树在内存中,便于操作:支持删除.修改.重新排列等多种功能. 通过树形结构存 ...

  3. 关于DOM的操作以及性能优化问题-重绘重排

     写在前面: 大家都知道DOM的操作很昂贵. 然后贵在什么地方呢? 一.访问DOM元素 二.修改DOM引起的重绘重排 一.访问DOM 像书上的比喻:把DOM和JavaScript(这里指ECMScri ...

  4. 读书笔记:JavaScript DOM 编程艺术(第二版)

    读完还是能学到很多的基础知识,这里记录下,方便回顾与及时查阅. 内容也有自己的一些补充. JavaScript DOM 编程艺术(第二版) 1.JavaScript简史 JavaScript由Nets ...

  5. 页面嵌入dom与被嵌入iframe的攻防

    1.情景一:自己的页面被引入(嵌入)至别人的页面iframe中 if(window.self != window.top){ //url是自己页面的url window.top.location.hr ...

  6. 通俗易懂的来讲讲DOM

    DOM是所有前端开发每天打交道的东西,但是随着jQuery等库的出现,大大简化了DOM操作,导致大家慢慢的“遗忘”了它的本来面貌.不过,要想深入学习前端知识,对DOM的了解是不可或缺的,所以本文力图系 ...

  7. HTML DOM 介绍

    本篇主要介绍DOM内容.DOM 节点.节点属性以及获取HTML元素的方法. 目录 1. 介绍 DOM:介绍DOM,以及对DOM分类和功能的说明. 2. DOM 节点:介绍DOM节点分类和节点层次. 3 ...

  8. HTML DOM 对象

    本篇主要介绍HTML DOM 对象:Document.Element.Attr.Event等4个对象. 目录 1. Document 对象:表示文档树的根节点,大部分属性和方法都是对元素进行操作. 2 ...

  9. 重撸js_2_基础dom操作

    1.node 方法 返回 含义 nodeName String 获取节点名称 nodeType Number 获取节点类型 nodeValue String 节点的值(注意:文本也是节点) 2.inn ...

随机推荐

  1. [转]notepad++各种插件

    http://www.crifan.com/files/doc/docbook/rec_soft_npp/release/htmls/npp_common_plugins.html

  2. rdd.toDebugString

    rdd.toDebugString 是个好东西,可以输出你的RDD的组成

  3. Hark的数据结构与算法练习之臭皮匠排序

    算法说明 个人感觉是没有意义的算法,只是用来作为学术研究.或者说开拓一下思维. 从wikipedia copy来的一句解释的话:Stooge排序是一种低效的递归排序算法,甚至慢于冒泡排序.在<算 ...

  4. include、include_once与require、require_once区别

    include与require的区别 include在引入不存文件时产生一个警告且脚本还会继续执行,而require则会导致一个致命性错误且脚本停止执行. <?php include 'no.p ...

  5. HDU4276 The Ghost Blows Light(树形DP+背包)

    题目大概说一棵n个结点树,每个结点都有宝藏,走过每条边要花一定的时间,现在要在t时间内从结点1出发走到结点n,问能获得最多的宝藏是多少. 放了几天的题,今天拿出来集中精力去想,还是想出来了. 首先,树 ...

  6. ZOJ1654 Place the Robots(二分图最大匹配)

    最大匹配也叫最大边独立集,就是无向图中能取出两两不相邻的边的最大集合. 二分图最大匹配可以用最大流来解. 如果题目没有墙,那就是一道经典的二分图最大匹配问题: 把地图上的行和列分别作为点的X部和Y部, ...

  7. 使用C++/C qsort 标准库对结构体进行快速排序

    C++标准快速排序库qsort进行结构体快速排序 代码如下 #include <stdio.h> #include <stdlib.h> typedef struct { in ...

  8. 【问题&解决】手机网页Html代码实现(解决显示页面很小的问题)

    工作需要,要做一个手机自适应的网页效果,终于搞定,先分享并记录! 其实主要就是改掉HTML页面声明: 在网页中加入以下代码,就可以正常显示了: <meta name="viewport ...

  9. FLTK 1.1.10 VS2010 Configuration 配置

    Download FLTK 1.1.10 at here. Download VS2010 Download CMake 2.8.12 I assume you've already installe ...

  10. HTML第一课总结

    1.图片热点: 规划出图片上的一个区域,可以做出超链接,直接点击图片区域就可以完成跳转的效果. 示例: 2.网页划区: 在一个网页里,规划出一个区域用来展示另一个网页的内容. 示例: 3.网页的拼接: ...