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 IOException, XMLParseException {
021 return read(new StringReader(xml_text.toString()));
022 }
023 public static TagElement read(URL url) throws IOException, XMLParseException {
024 return read(url.openStream());
025 }
026 public static TagElement read(URL url, String encoding) throws IOException, XMLParseException {
027 return read(url.openStream(), encoding);
028 }
029 public static TagElement read(String file_name_or_url) throws IOException, XMLParseException {
030 return read(findURL(file_name_or_url));
031 }
032 public static TagElement read(String file_name_or_url, String encoding) throws IOException, XMLParseException {
033 return read(new URL(file_name_or_url), encoding);
034 }
035 public static TagElement read(File file) throws IOException, XMLParseException {
036 return read(file.toURI().toURL());
037 }
038 public static TagElement read(File file, String encoding) throws IOException, XMLParseException {
039 return read(file.toURI().toURL(), encoding);
040 }
041 public static TagElement read(InputStream in, String encoding) throws IOException, XMLParseException {
042 return read(new InputStreamReader(in, encoding));
043 }
044 public static TagElement read(InputStream in) throws IOException, XMLParseException {
045 ElementParser parser = new ElementParser(in);
046 parser.setPolicy(new XMLParserPolicy());
047 parser.parse();
048 return parser.getFirstPlainTagElement();
049 }
050 public static TagElement read(Reader r) throws IOException, XMLParseException {
051 ElementParser parser = new ElementParser(r);
052 parser.setPolicy(new XMLParserPolicy());
053 parser.parse();
054 return parser.getFirstPlainTagElement();
055 }
056
057 protected static URL findURL(String name) throws IOException, XMLParseException {
058 File file = new File(name);
059 if(file.exists()) {
060 return file.toURI().toURL();
061 }
062 URL url = ClassLoader.getSystemResource(name);
063 if(url != null) {
064 return url;
065 }
066 throw new IOException("cannot find resource: "+name);
067 }
068
069 public static void write(File file, Element element) throws IOException, XMLParseException {
070 write(new FileWriter(file), element);
071 }
072
073 public static void write(Writer writer, Element element) throws IOException, XMLParseException {
074 element.write(writer);
075 }
076 }