001 /* 002 * To change this template, choose Tools | Templates 003 * and open the template in the editor. 004 */ 005 006 package org.util.xml.io; 007 008 import org.util.xml.parse.policy.*; 009 import org.util.xml.parse.*; 010 import org.util.xml.element.*; 011 import java.net.*; 012 import java.io.*; 013 014 /** 015 * 016 * @author masaru 017 */ 018 public class XMLIO { 019 020 public static TagElement read(StringBuffer xml_text) throws Exception { 021 ElementParser parser = new ElementParser(new StringReader(xml_text.toString())); 022 parser.setPolicy(new XMLParserPolicy()); 023 parser.parse(); 024 return parser.getFirstPlainTagElement(); 025 } 026 public static TagElement read(URL url) throws Exception { 027 ElementParser parser = new ElementParser(url.openStream()); 028 parser.setPolicy(new XMLParserPolicy()); 029 parser.parse(); 030 return parser.getFirstPlainTagElement(); 031 } 032 public static TagElement read(URL url, String encoding) throws Exception { 033 ElementParser parser = new ElementParser(url.openStream(), encoding); 034 parser.setPolicy(new XMLParserPolicy()); 035 parser.parse(); 036 return parser.getFirstPlainTagElement(); 037 } 038 public static TagElement read(String file_name_or_url) throws Exception { 039 return read(findURL(file_name_or_url)); 040 } 041 public static TagElement read(String file_name_or_url, String encoding) throws Exception { 042 return read(new URL(file_name_or_url), encoding); 043 } 044 public static TagElement read(File file) throws Exception { 045 return read(file.toURI().toURL()); 046 } 047 public static TagElement read(File file, String encoding) throws Exception { 048 return read(file.toURI().toURL(), encoding); 049 } 050 051 protected static URL findURL(String name) throws Exception { 052 File file = new File(name); 053 if(file.exists()) 054 return file.toURI().toURL(); 055 URL url = ClassLoader.getSystemResource(name); 056 if(url != null) 057 return url; 058 throw new Exception("cannot find resource: "+name); 059 } 060 061 062 public static void write(File file, Element element) throws Exception { 063 write(new FileWriter(file), element); 064 } 065 public static void write(Writer writer, Element element) throws Exception { 066 element.write(writer); 067 } 068 }