我给你来一个<?xml version="1.0"?>
<!DOCTYPE document [
<!ELEMENT document (employee*)>
<!ELEMENT employee (id, first_name, second_name, birthday, title, salary)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT first_name (#PCDATA)>
<!ELEMENT second_name (#PCDATA)>
<!ELEMENT birthday (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT salary (#PCDATA)>
<!ELEMENT company (#PCDATA)>
]>
<document>
<company>MyCompany</company>
<employee>
<id>0799</id>
<first_name>Jack</first_name>
<second_name>Smith</second_name>
<birthday>12/28/75</birthday>
<title>Manager</title>
<salary>$7000.00</salary>
</employee>
<employee>
<id>0645</id>
<first_name>Gerald</first_name>
<second_name>Johnson</second_name>
<birthday>03/05/76</birthday>
<title>Keyboard Operator</title>
<salary>$4500.00</salary>
</employee>
<employee>
<id>0009</id>
<first_name>Mike</first_name>
<second_name>David</second_name>
<birthday>04/18/78</birthday>
<title>Tester</title>
<salary>$3000.00</salary>
</employee>
<employee>
<id>0010</id>
<first_name>Keane</first_name>
<second_name>Dennis</second_name>
<birthday>8/18/74</birthday>
<title>Engineer</title>
<salary>$5500.00</salary>
</employee>
</document>

解决方案 »

  1.   

    faint,人家要对xml文档进行write操作的代码可实现的方法很多啊,那种都行?
      

  2.   

    package myxml;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.apache.crimson.tree.*;
    import java.io.*;
    import java.util.*;/**
     * <p>Title: </p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2002</p>
     * <p>Company: </p>
     * @author xxy
     * @version 1.0
     */public class XMLFromJdbc implements Serializable{
       private PeopleProcessor dbProcessor;
       private  Document doc;
       private List peopleList;
       private boolean isDocCreated=false;   public XMLFromJdbc() throws Exception{
          dbProcessor=new PeopleProcessor();
          peopleList=dbProcessor.retrievePeople();     //执行select * from people
          dbProcessor.close();      DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
          DocumentBuilder builder=factory.newDocumentBuilder();
          doc=builder.newDocument();
       }   public void createDocument(){
          if(doc==null) return;
          if(isDocCreated) return;
          Element peopleElement=doc.createElement(XMLTagDir.NODE_PEOPLE);      if(peopleList==null) return;
          Iterator iter=peopleList.iterator();       //游标Iterator
          int no=1;
          while(iter.hasNext()){ //Tierator的方法hasNext()
             DBPeople people=(DBPeople)iter.next(); //Tierator的方法Next()         Element personElement=doc.createElement(XMLTagDir.NODE_PERSON);
             personElement.setAttribute("PERSONID","E"+no);         //one person include several tags
             Text text=null;
             Element name=doc.createElement(XMLTagDir.NODE_NAME);
             text=doc.createTextNode(people.getName());
             name.appendChild(text);
             personElement.appendChild(name);         Element address=doc.createElement(XMLTagDir.NODE_ADDRESS);
             text=doc.createTextNode(people.getAddress());
             address.appendChild(text);
             personElement.appendChild(address);         Element tel=doc.createElement(XMLTagDir.NODE_TEL);
             text=doc.createTextNode(people.getTel());
             tel.appendChild(text);
             personElement.appendChild(tel);         Element fax=doc.createElement(XMLTagDir.NODE_FAX);
             text=doc.createTextNode(people.getFax());
             fax.appendChild(text);
             personElement.appendChild(fax);         Element email=doc.createElement(XMLTagDir.NODE_EMAIL);
             text=doc.createTextNode(people.getEmail());
             email.appendChild(text);
             personElement.appendChild(email);         peopleElement.appendChild(personElement);
             no++;
          }
          doc.appendChild(peopleElement);
          isDocCreated=true;
       }   public void saveDocument(String path) throws IOException {
          FileWriter fout=new FileWriter(path);
          XmlDocument xmldoc=(XmlDocument)doc;
          xmldoc.write(fout);
          fout.close();
       }   public Document getDocument(){
          if(!isDocCreated)
             this.createDocument();
          return this.doc;
       }
       public static void main(String[] args) {
          try{
             XMLFromJdbc doc = new XMLFromJdbc();
             doc.createDocument();
             System.out.println("doc created");
     //        String path="e:/houjie/JavaAdvance/dist/xmldoc/XMLFromJdbc.xml";
             String path="e:/jhb1117/classes/xmldoc/XMLFromJdbc.xml";
             doc.saveDocument(path);
             System.out.println("file saved");         System.out.println(doc.peopleList.size());   //
          }catch(Exception e){
             e.printStackTrace();
          }
       }
    }
      

  3.   

    /**
         * This method removes a child element from a document.  The document
         * should be of the format created in Listing 2.
         * This method corresponds to Listin 4.
         * @param myDocument the JDOM document built from Listing 2.
         */
        public static void removeChildElement(Document myDocument) {
            //some setup
            System.out.println("About to remove the year element.\nThe current document:");
            outputDocument(myDocument);
            Element carElement = myDocument.getRootElement();        //remove a child Element
            boolean removed = carElement.removeChild("year");        //show success or failure
            if(removed) {
                System.out.println("Here is the modified document without year:");
                outputDocument(myDocument);
            } else {
                System.out.println("Something happened.  We were unable to remove the year element.");
            }
        }    /**
         * This method shows how to use XMLOutputter to output a JDOM document to
         * the stdout.
         * This method corresponds to Listing 5.
         * @param myDocument the JDOM document built from Listing 2.
         */
        public static void outputDocument(Document myDocument) {
            try {
                XMLOutputter outputter = new XMLOutputter("  ", true);
                outputter.output(myDocument, System.out);
            } catch (java.io.IOException e) {
                e.printStackTrace();
            }
        }
      

  4.   

    /**
         * This method shows how to use XMLOutputter to output a JDOM document to
         * a file located at xml/myFile.xml.
         * This method corresponds to Listing 6.
         * @param myDocument the JDOM document built from Listing 2.
         */
        public static void outputDocumentToFile(Document myDocument) {
            //setup this like outputDocument
            try {
                XMLOutputter outputter = new XMLOutputter("  ", true);            //output to a file
                FileWriter writer = new FileWriter("xml/myFile.xml");
                outputter.output(myDocument, writer);
                writer.close();        } catch(java.io.IOException e) {
                e.printStackTrace();
            }
        }    /**
         * This method takes a JDOM document in memory, an xsl file at xml/car.xsl,
         * and outputs the results to stdout.
         * This method corresponds to Listing 9.
         * @param myDocument the JDOM document built from Listing 2.
         */
        public static void executeXSL(Document myDocument) {
    try {
    TransformerFactory tFactory = TransformerFactory.newInstance();
                // Make the input sources for the XML and XSLT documents
                org.jdom.output.DOMOutputter outputter = new org.jdom.output.DOMOutputter();
                org.w3c.dom.Document domDocument = outputter.output(myDocument);
                javax.xml.transform.Source xmlSource = new javax.xml.transform.dom.DOMSource(domDocument);
                StreamSource xsltSource = new StreamSource(new FileInputStream("xml/car.xsl"));
    //Make the output result for the finished document
                /*
                 * Note that here we are just going to output the results to the
                 * System.out, since we don't actually have a HTTPResponse object
                 * in this example
                 */
                //StreamResult xmlResult = new StreamResult(response.getOutputStream());
                StreamResult xmlResult = new StreamResult(System.out);
    //Get a XSLT transformer
    Transformer transformer = tFactory.newTransformer(xsltSource);
    //do the transform
    transformer.transform(xmlSource, xmlResult);
            } catch(FileNotFoundException e) {
                e.printStackTrace();
            } catch(TransformerConfigurationException e) {
                e.printStackTrace();
    } catch(TransformerException e) {
                e.printStackTrace();
            } catch(org.jdom.JDOMException e) {
                e.printStackTrace();
            }
    }    /**
         * Main method that allows the various methods to be used.
         * It takes a single command line parameter.  If none are
         * specified, or the parameter is not understood, it prints
         * its usage.
         */
        public static void main(String argv[]) {
            if(argv.length == 1) {
                String command = argv[0];
                if(command.equals("create")) outputDocument(createDocument());
                else if(command.equals("access")) accessChildElement(createDocument());
                else if(command.equals("remove")) removeChildElement(createDocument());
                else if(command.equals("output")) outputDocument(createDocument());
                else if(command.equals("file")) outputDocumentToFile(createDocument());
                else if(command.equals("read")) outputDocument(readDocument());
                else if(command.equals("xsl")) executeXSL(createDocument());
                else {
                    System.out.println(command + " is not a valid option.");
                    printUsage();
                }
            } else {
                printUsage();
            }
        }    /**
         * Convience method to print the usage options for the class.
         */
        public static void printUsage() {
            System.out.println("Usage: Article [option] \n where option is one of the following:");
            System.out.println("  create - create a document as shown in Listing 2");
            System.out.println("  access - access a child element as shown in Listing 3");
            System.out.println("  remove - remove a child element as shown in Listing 4");
            System.out.println("  output - output a document to the console as shown in Listing 5");
            System.out.println("  file   - output a document to xml/myFile.xml as shown in Listing 6");
            System.out.println("  read   - parse a document from xml/sample.xml as shown in Listing 7");
            System.out.println("  xsl    - transform a document as shown in Listing 9");
        }
    }