XML to XML 转换的类

/**
 * <p>
 * Title: Parser类
 * </p>
 * <p>
 * Description: xml之间转换主类
 * </p>
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * <p>
 * 
 * </p>
 *
 * 
 * @version 1.0
 */

public class Parser {
 //存放规则文件schema文件的绝对路径
 private String ruleSchemaPath;
 //存放规则文件的绝对路径
 private String rulePath;
 //存放源文件的绝对路径
 private String sourcePath;
 //存放结果文件的绝对路径
 private String targetFileFullName;
 //存放根据规则文件生成的Document对象
 private Document doc;
 
 
 public String getRuleSchemaPath() {
  return ruleSchemaPath;
 }
/**
 * 设置规则文件schema的绝对路径
 * @param ruleSchemaPath
 */
 public void setRuleSchemaPath(String ruleSchemaPath) {
  this.ruleSchemaPath = ruleSchemaPath;
 }

 public Document getDoc() {
  return doc;
 }

 public void setDoc(Document doc) {
  this.doc = doc;
 }

 public String getSourcePath() {
  return sourcePath;
 }
/**
 * 设置源xml文件的绝对路径
 * @param sourcePath
 */
 public void setSourcePath(String sourcePath) {
  this.sourcePath = sourcePath;
 }

 public String getTargetFileFullName() {
  return targetFileFullName;
 }
/**
 * 设置要生成的目标xml文件的名称,是绝对路径
 * @param targetFileFullName 要生成的目标xml文件的绝对路径
 */

 public void setTargetFileFullName(String targetFileFullName) {
  this.targetFileFullName = targetFileFullName;
 }

 public String getRulePath() {
  return rulePath;
 }
/**
 * 设置规则文件的绝对路径
 * @param rulePath 规则文件的绝对路径
 */
 public void setRulePath(String rulePath) {
  this.rulePath = rulePath;
 }

 public Parser() {
  super();
  // TODO Auto-generated constructor stub
 }
/**
 * 从一个文件路径里读取一个Document
 * @param fileName 文件的绝对路径
 * @return Document
 */
 private Document read(String fileName){
  SAXReader reader = new SAXReader();
  Document document = null;
  try {
   document = reader.read(new File(fileName));
   
  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
  return document;
  
 }


 /**
  * 根据schema文件验证规则文件是否合法,如果合法,返回true;否则返回false.
  * @param xsdPath  schema文件的绝对路径
  * @param xmlPath  欲验证的xml文件的绝对路径
  * @return 如果xml文件符合指定的schema文件要求,返回true;否则返回false.
  */
 private boolean validateXmlByXsd(String xsdPath,String xmlPath){
  boolean isOK = false;
  File xmlFile = new File(xmlPath);
  File xsdFile = new File(xsdPath);
  if(!xmlFile.exists() || !xsdFile.exists()){
   return isOK;
  }
  SAXParserFactory factory = SAXParserFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setValidating(true);
  
  try {
   SAXParser parser = factory.newSAXParser();
   parser.setProperty(StaticConstant.SCHEMA_LANGUAGE, StaticConstant.XML_SCHEMA);
   parser.setProperty(StaticConstant.SCHEMA_SOURCE, xsdFile);
   
   XMLReader xmlReader = parser.getXMLReader();
   xmlReader.setContentHandler(new DefaultHandler());
   xmlReader.setErrorHandler(new DefaultErrorHandler());
   xmlReader.parse(xmlPath);
   isOK = true;
   
   
  } catch (ParserConfigurationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SAXException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return isOK;
 }
 /**
  * 读取规则文件和源文件生成目标文件的Document
  * @return 目标文件的Document.
  */
 private Document parseRuleXml(){
  //首先根据规则文件的schema验证规则文件是否正确,若不正确直接抛错误。
  if(validateXmlByXsd(getRuleSchemaPath(), getRulePath())){//如果验证正确
   Document rule = read(rulePath);
   Document source = read(sourcePath);
   Element ruleRoot = rule.getRootElement();
   List children = ruleRoot.selectNodes("/rule/children");
   for(int i=0,l=children.size();i<l;i++){
    Element child = (Element)children.get(i);
    if(doc == null){
     doc = DocumentHelper.createDocument();
    }
    Iterator childIt = child.elementIterator();
    XpathParser xp = new XpathParser();
    xp.setFromDocument(source);
    xp.setTargetDocument(doc);
    
    while(childIt.hasNext()){
     Element el = (Element)childIt.next();
     String text = el.getText();
     
     if(el.getName().equals("parent_from")){
      
      xp.setParentFrom(text);
      
     }else if(el.getName().equals("parent_to")){
      xp.setParentTo(text);
     }else if(el.getName().equals("from")){
      xp.setFrom(text);
     }else if(el.getName().equals("to")){
      xp.setTo(text);
     }
    }
    doc = xp.getTargetDocument();
   }
   
  } else
   try {
    throw new Exception("规则文件不符合它的schema,请重新写规则文件并用其schema做验证!");
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  return doc;
 }
/**
 * 生成目标XML文件,如果成功生成,返回true;否则返回false.
 * @return boolean
 */
 public boolean toXML(){
  boolean isOK = false;
  //创建XML文档
  OutputFormat format = OutputFormat.createPrettyPrint();
  format.setEncoding("UTF-8");
  try {
   Document doc = parseRuleXml();
   XMLWriter writer = new XMLWriter(new FileOutputStream(getTargetFileFullName()),format);
   writer.write(doc);
   writer.close();
   isOK = true;
  }  catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
  return isOK;
  
 }
 
 public static void main(String[] args){
  Parser parser = new Parser();
  parser.setRuleSchemaPath("F:\\ESB\\example\\rule.xsd");
  parser.setRulePath("F:\\ESB\\example\\rule.xml");
  parser.setSourcePath("F:\\ESB\\example\\source.xml");
  parser.setTargetFileFullName("F:\\ESB\\example\\result.xml");
  if(parser.toXML()){
   System.out.println("成功生成XML!!!");
  }else{
   System.out.println("生成XML出现错误!!!");
  }
 }
}

 

/**
 * <p>
 * Title: XpathParser类
 * </p>
 * <p>
 * Description: 根据xpath读取目标文件里的数据,同时根据描述目标文件的xpath生成目标文件的Document。
 * </p>
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * <p>
 * 
 * </p>
 *
 *  * @version 1.0
 */
public class XpathParser {
//规则文件中源文件的父路径
 private String parentFrom;
 //规则文件中源文件本身路径
 private String from;
 //规则文件中目标文件的父路径
 private String parentTo;
 //规则文件中目标文件路径本身
 private String to;
 //源文件Document
 private Document fromDocument;
 //目标文件Document
 private Document doc;

 public String getParentFrom() {
  return parentFrom;
 }


 public void setParentFrom(String parentFrom) {
  this.parentFrom = parentFrom;
 }


 public String getFrom() {
  return from;
 }


 public void setFrom(String from) {
  this.from = from;
 }


 public String getParentTo() {
  return parentTo;
 }


 public void setParentTo(String parentTo) {
  this.parentTo = parentTo;
 }


 public String getTo() {
  return to;
 }


 public void setTo(String to) {
  this.to = to;
 }

 public void setFromDocument(Document source) {
  // TODO Auto-generated method stub
  this.fromDocument = source;
 }


 public Document getFromDocument() {
  return fromDocument;
 }


 public void setTargetDocument(Document doc) {
  // TODO Auto-generated method stub
  this.doc = doc;
 }

/**
 * 根据规则文件生成目标文件的Document
 * @return
 */
 public Document getTargetDocument() {
  // TODO Auto-generated method stub
  String parentPath = "";
  if(this.parentTo == null || this.parentTo.equals("")){
   if(this.to != null && !this.to.equals("")){
    if(this.to.startsWith(StaticConstant.SLASH)){//表示to指的是绝对路径
     parentPath = this.to;
    } else
     try {
      throw new Exception("没有父路径的情况下,此目标路径必须为绝对路径!");
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    
   } else
    try {
     throw new Exception("目标路径不能为空!");
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }else if(this.parentTo != null){
   if(this.parentTo.startsWith(StaticConstant.SLASH)){//表示父路径xpath是绝对路径
    if(this.to != null && !this.to.equals("")){
     if(this.to.startsWith(StaticConstant.SLASH)){//表示to指的是绝对路径
      parentPath = this.to;
     }else{
      parentPath = this.parentTo.concat(StaticConstant.SLASH).concat(this.to);//表示to指的是相对路径
     }
     
    }else
     new Exception("必须要有子路径!");
   } else
    try {
     throw new Exception("父路径必须为绝对路径!");
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
    String[] parents = parentPath.substring(1).split(StaticConstant.SLASH);
    String temp = "";
    Element parentElement = null;
    for(int i=0,l=parents.length;i<l;i++){
     String parent = parents[i];
     
     temp += StaticConstant.SLASH + parent;
     if(this.doc.selectNodes(temp).isEmpty()){
      if(parent.indexOf(StaticConstant.LEFT_MIDDLE_BRACKET) != -1){//表示有属性
       String p[] = parent.split("\\" + StaticConstant.LEFT_MIDDLE_BRACKET);
       if(parentElement == null ){
        parentElement = this.doc.addElement(p[0]);
        
       }else{
        parentElement = parentElement.addElement(p[0]);
       }
       String attr = p[1].substring(1, p[1].length()-1);
       parentElement.addAttribute(attr.substring(0,attr.indexOf("=")), attr.substring(attr.indexOf("=")+2,attr.length()-1));
       
       
      }else{
       if(parentElement == null ){
        parentElement = this.doc.addElement(parent);
        
       }else{
        parentElement = parentElement.addElement(parent);
       }
      }
      
     }else {
      parentElement = (Element)this.doc.selectSingleNode(temp);
     }
     
     
    }
    //读源里的值
    String fromPath = "";
    if(this.parentFrom == null || this.parentFrom.equals("")){
     if(this.from != null && !this.from.equals("")){
      if(this.from.startsWith(StaticConstant.SLASH)){//表示from指的是绝对路径
       fromPath = this.from;
      }else{
       try {
        throw new Exception("没有父路径的情况下,此目标路径必须为绝对路径!");
       } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
     } else
      try {
       throw new Exception("必须要有子路径!");
      } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
    }else if(this.parentFrom != null){
     if(this.parentFrom.startsWith(StaticConstant.SLASH)){//表示xpath是绝对路径
      if(this.from != null && !this.from.equals("")){
       if(this.from.startsWith(StaticConstant.SLASH)){//表示from指的是绝对路径
        fromPath = this.from;
       }else{
        fromPath = this.parentFrom.concat(StaticConstant.SLASH).concat(this.from);//表示from指的是相对路径
       }
      } else
       try {
        throw new Exception("必须要有子路径!");
       } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
     } else
      try {
       throw new Exception("父路径必须为绝对路径!");
      } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      
    }
    String text = this.fromDocument.selectSingleNode(fromPath).getText();
    this.doc.selectSingleNode(parentPath).setText(text);
    
  return this.doc;
 }
 
}

 

/**
 * <p>
 * Title: StaticConstant类
 * </p>
 * <p>
 * Description: 静态常量
 * </p>
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * <p>
 *
 * </p>
 *
 * 
 * @version 1.0
 */
public class StaticConstant {

 public static final String LEFT_BRACKET = "<";
 public static final String RIGHT_BRACKET = ">";
 public static final String SLASH = "/";
 public static final String LEFT_MIDDLE_BRACKET = "[";
 public static final String blank =" ";
 public static final String SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
 public static final String XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
 public static final String SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
}

测试类

public class MainTest extends  TestCase{

 public void test(){
  Parser parser = new Parser();
  parser.setRuleSchemaPath("F:\\ESB\\example\\rule.xsd");
  parser.setRulePath("F:\\ESB\\example\\rule.xml");
  parser.setSourcePath("F:\\ESB\\example\\source.xml");
  parser.setTargetFileFullName("F:\\ESB\\example\\result.xml");
  if(parser.toXML()){
   System.out.println("成功生成XML!!!");
  }else{
   System.out.println("生成XML出现错误!!!");
  }
  
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值