1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | import javax.xml.stream.*; public class XMLWriter { // Namespaces private static final String GARDENING = "http://com.bdaum.gardening"; private static final String XHTML = "http://www.w3.org/1999/xhtml"; public static void main(String[] args) throws XMLStreamException { // Create an output factory XMLOutputFactory xmlof = XMLOutputFactory.newInstance(); // Set namespace prefix defaulting for all created writers xmlof.setProperty("javax.xml.stream.isPrefixDefaulting",Boolean.TRUE); // Create an XML stream writer XMLStreamWriter xmlw = xmlof.createXMLStreamWriter(System.out); // Write XML prologue xmlw.writeStartDocument(); // Write a processing instruction xmlw.writeProcessingInstruction( "xml-stylesheet href='catalog.xsl' type='text/xsl'"); // Now start with root element xmlw.writeStartElement("product"); // Set the namespace definitions to the root element // Declare the default namespace in the root element xmlw.writeDefaultNamespace(GARDENING); // Writing a few attributes xmlw.writeAttribute("productNumber","3923-1"); xmlw.writeAttribute("name","Nightshadow"); // Declare XHTML prefix // xmlw.setPrefix("xhtml",XHTML); // Different namespace for description element xmlw.writeStartElement(XHTML,"description"); // Declare XHTML namespace in the scope of the description element // xmlw.writeNamespace("xhtml",XHTML); xmlw.writeCharacters( "A tulip of almost black color. \nBlossoms in April & May"); xmlw.writeEndElement(); // Shorthand for empty elements xmlw.writeEmptyElement("supplier"); xmlw.writeAttribute("name","Floral22"); // xmlw.writeEndElement(); // Write document end. This closes all open structures xmlw.writeEndDocument(); // Close the writer to flush the output xmlw.close(); } } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |