Java Tutorial/XML/XML Serialization

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Create an XML document with DOM

import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Document doc = impl.createDocument(null, null, null);
    Element e1 = doc.createElement("api");
    doc.appendChild(e1);
    Element e2 = doc.createElement("java");
    e1.appendChild(e2);
    e2.setAttribute("url", "http://www.domain.ru");
    DOMSource domSource = new DOMSource(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);
    System.out.println(sw.toString());
  }
}





Extracting an XML formatted string out of a DOM object

import java.io.StringWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class Main {
  public static void main(String[] argv) throws Exception {
  }
  static String getXMLString(Document xmlDoc) throws Exception {
    StringWriter writer = null;
    DOMSource source = new DOMSource(xmlDoc.getDocumentElement());
    writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.transform(source, result);
    StringBuffer strBuf = writer.getBuffer();
    return strBuf.toString();
  }
}





PropsToXML takes a standard Java properties file, and converts it into an XML file

/*--
 Copyright (C) 2001 Brett McLaughlin.
 All rights reserved.
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions, and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions, and the disclaimer that follows
    these conditions in the do*****entation and/or other materials
    provided with the distribution.
 3. The name "Java and XML" must not be used to endorse or promote products
    derived from this software without prior written permission.  For
    written permission, please contact brett@newInstance.ru.
 In addition, we request (but do not require) that you include in the
 end-user do*****entation provided with the redistribution and/or in the
 software itself an acknowledgement equivalent to the following:
     "This product includes software developed for the
      "Java and XML" book, by Brett McLaughlin (O"Reilly & Associates)."
 THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED.  IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.
 */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.jdom.Do*****ent;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
/**
 * <b><code>PropsToXML</code></b> takes a standard Java properties
 *   file, and converts it into an XML format. This makes properties
 *   like <code>enhydra.classpath.separator</code> "groupbable" by
 *   "enhydra", "classpath", and by the key name, "separator", which
 *   the standard Java <code>java.util.Properties</code> class does
 *   not allow.
 */
public class Main {
    /**
     * <paragraph> This will take the supplied properties file, and
     *   convert that file to an XML representation, which is
     *   then output to the supplied XML do*****ent filename. </paragraph>
     *
     * @param propertiesFilename file to read in as Java properties.
     * @param xmlFilename file to output XML representation to.
     * @throws <code>IOException</code> - when errors occur.
     */
    public void convert(String propertiesFilename, String xmlFilename)
        throws IOException {
        // Get Java Properties object
        FileInputStream input = new FileInputStream(propertiesFilename);
        Properties props = new Properties();
        props.load(input);
        // Convert to XML
        convertToXML(props, xmlFilename);
    }
    /**
     * <paragraph> This will handle the detail of conversion from a Java
     *  <code>Properties</code> object to an XML do*****ent. </paragraph>
     *
     * @param props <code>Properties</code> object to use as input.
     * @param xmlFilename file to output XML to.
     * @throws <code>IOException</code> - when errors occur.
     */
    private void convertToXML(Properties props, String xmlFilename)
        throws IOException {
        // Create a new JDOM Do*****ent with a root element "properties"
        Element root = new Element("properties");
        Do*****ent doc = new Do*****ent(root);
        // Get the property names
        Enumeration propertyNames = props.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyName = (String)propertyNames.nextElement();
            String propertyValue = props.getProperty(propertyName);
            createXMLRepresentation(root, propertyName, propertyValue);
        }
        // Output do*****ent to supplied filename
        XMLOutputter outputter = new XMLOutputter("  ", true);
        FileOutputStream output = new FileOutputStream(xmlFilename);
        outputter.output(doc, output);
    }
    /**
     * <paragraph> This will convert a single property and its value to
     *  an XML element and textual value. </paragraph>
     *
     * @param root JDOM root <code>Element</code> to add children to.
     * @param propertyName name to base element creation on.
     * @param propertyValue value to use for property.
     */
    private void createXMLRepresentation(Element root,
                                         String propertyName,
                                         String propertyValue) {
        /*
        Element element = new Element(propertyName);
        element.setText(propertyValue);
        root.addContent(element);
        */
        int split;
        String name = propertyName;
        Element current = root;
        Element test = null;
        while ((split = name.indexOf(".")) != -1) {
            String subName = name.substring(0, split);
            name = name.substring(split+1);
            // Check for existing element
            if ((test = current.getChild(subName)) == null) {
                Element subElement = new Element(subName);
                current.addContent(subElement);
                current = subElement;
            } else {
                current = test;
            }
        }
        // When out of loop, what"s left is the final element"s name
        Element last = new Element(name);
        // last.setText(propertyValue);
        last.setAttribute("value", propertyValue);
        current.addContent(last);
    }
    /**
     * <paragraph> Provide a static entry point for running. </paragraph>
     */
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java javaxml2.PropsToXML " +
                "[properties file] [XML file for output]");
            System.exit(0);
        }
        try {
            PropsToXML propsToXML = new PropsToXML();
            propsToXML.convert(args[0], args[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*   Java and XML, Second Edition
 *   Solutions to Real-World Problems
 *   By Brett McLaughlin
 *   Second Edition August 2001
 *   ISBN: 0-596-00197-5
 *   http://www.oreilly.ru/catalog/javaxml2/
 */





Saving a DOM tree to XML file javax.xml.parsers (JAXP)

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder loader = factory.newDocumentBuilder();
    Document document = loader.newDocument();
    Element order = document.createElement("order");
    document.appendChild(order);
    XMLSerializer serializer = new XMLSerializer();
    serializer.setOutputCharStream(new java.io.FileWriter("order.xml"));
    serializer.serialize(document);
  }
}





Strip extra spaces in a XML string

public class Main {
  public static void main(String[] args) {
    String xml = "<a>test 1</a>    <b>test 2</b> ";
    String out = xml.replaceAll(">\\s+<", "><");
    System.out.println(xml);
    System.out.println(out);
  }
}





Writing a DOM Document to an XML File

import java.io.File;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class Main {
  public static void main(String[] argv) throws Exception {
    Document doc = null;
    String filename = "name.xml";
    Source source = new DOMSource(doc);
    File file = new File(filename);
    Result result = new StreamResult(file);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
  }
}





Writing Only the Text of a DOM Document

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(OutputKeys.METHOD, "text");
    Source source = new DOMSource(doc);
    Result result = new StreamResult(new File("outfilename.xml"));
    xformer.transform(source, result);
  }
}