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. FZU 2183 字符串处理

    Problem Description 现在有一些被简单压缩的字符串,例如:a[120]代表120个a.对于字符串acb[3]d[5]e相对于acbbbddddde 现在给你两个字符串cString, ...

  2. 移动开单软件 手持PDA开单扫描打印系统开发介绍

    具体功能预览--(图示) PDA开单打印扫描采集器主程序: ▲门店使用:接单员销售开单.销售退货或查询相关资料. ▲仓库使用:PDA仓库验收货.发货.仓库盘点 ▲在外业务开单:业务在外面开销售单.销售 ...

  3. SPOJ839 Optimal Marks(最小割)

    题目大概说给一张图,每个点都有权,边的权等于其两端点权的异或和,现已知几个点的权,为了使所有边的边权和最小,其他点的权值该是多少. 很有意思的一道题,完全看不出和网络流有什么关系. 考虑每个未知的点$ ...

  4. 剪花布条[HDU2087]

    剪花布条 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submi ...

  5. unity scroolView 和 groupview

    #pragma strict var scrollPosition:Vector2; function Start () { scrollPosition[0]=50; scrollPosition[ ...

  6. BZOJ1397 : Ural 1486 Equal squares

    二分答案mid,然后检验是否存在两个相同的mid*mid的正方形 检验方法: 首先对于每个位置,求出它开始长度为mid的横行的hash值 然后对于hash值再求一次竖列的hash值 将第二次求出的ha ...

  7. jQuery Event.delegateTarget 属性详解

    // 为id为element的元素中的所有span元素绑定click事件 $("#element").on( "click", "span" ...

  8. TextBlock 格式化内容

    Text="{Binding ContentName,StringFormat=分享好书\{0\}}"

  9. 关于inf的问题

    详见实例 #include<algorithm> #include<iostream> #include<cstring> #include<cstdio&g ...

  10. JS中检测数据类型的四种方式及每个方式的优缺点

    //1.typeof 用来检测数据类型的运算符 //->typeof value //->返回值首先是一个字符串,其次里面包含了对应的数据类型,例如:"number". ...