⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 manytomanyxmldata.java

📁 此程序都是企业级 的数据库开发程序 全面揭示了JAVA对数据库的操作
💻 JAVA
字号:
import java.sql.*;                   /* JDBC Classes */
import org.w3c.dom.*;                /* W3C Interfaces */
import org.apache.xerces.dom.*;      /* Xerces DOM Classes */
import org.apache.xml.serialize.*;   /* Xerces serializer */
import java.io.*;                    /* Java io classes for file reading/writing */
import org.apache.xpath.XPathAPI;    /* Xalan XPath Classes */

public class ManyToManyXmlData {

  /* Note we are connecting to a different database then the previous examples */
  public static final String JDBCURL = "jdbc:cloudscape:c:/wrox/database/BegJDB";
  public static final String JDBCDRIVER = "COM.cloudscape.core.JDBCDriver";
  public static StringBuffer SQL = new StringBuffer("");
  public static String OUTPUTFILE = "c:\\customerAddress.xml";

  private static void initializeSQL() {
    SQL.append("SELECT                          ");
    SQL.append("  Customers.customerid,         ");
    SQL.append("  Customers.customerfirstname,  ");
    SQL.append("  Customers.customerlastname,   ");
    SQL.append("  Addresses.addressid,          ");
    SQL.append("  Addresses.address1,           ");
    SQL.append("  Addresses.address2,           ");
    SQL.append("  Addresses.addresstype,        ");
    SQL.append("  PostalCodes.city,             ");
    SQL.append("  PostalCodes.stateprov,        ");
    SQL.append("  Addresses.PostalCode          ");
    SQL.append("FROM                            ");
    SQL.append("  Customers,                    ");
    SQL.append("  CustomerAddresses,            ");
    SQL.append("  Addresses,                    ");
    SQL.append("  PostalCodes                   ");
    SQL.append("WHERE                           ");
    SQL.append("  Customers.customerid =        ");
    SQL.append("  CustomerAddresses.customerid  ");
    SQL.append("AND                             ");
    SQL.append("  CustomerAddresses.addressid = ");
    SQL.append("  Addresses.addressid           ");
    SQL.append("AND                             ");
    SQL.append("  Addresses.postalcode=         ");
    SQL.append("  PostalCodes.postalcode        ");
    SQL.append("ORDER BY                        ");
    SQL.append("  Customers.customerid  ASC      ");
  } 

  public static void main(String args[]) {
    try {

      /**
       * ****Step 1 - Making my JDBC Connection to Cloudscape****
       */
      Class.forName(JDBCDRIVER).newInstance();
      Connection conn = DriverManager.getConnection(JDBCURL);

      /**
       * ****Step 2 - Retrieve my customer address data from the database****
       */
      initializeSQL();
      Statement statement = conn.createStatement();
      ResultSet customerAddressRS = statement.executeQuery(SQL.toString());

      /**
       * ****Step 3 - Build invoice XML DOM.****
       */
      Document xmlDoc = buildCustomerAddressXML(customerAddressRS);

      /**
       * ****Step 4 - Writing the output to a file ****
       */
      File outputFile = new File(OUTPUTFILE);
      printDOM(xmlDoc, outputFile);

      customerAddressRS.close();   /* Closing my result set */
    } catch (Exception e) {
      System.out.println("Really poor exception handling: " + e.toString());
    } 
  } 

  /*
   * The buildCustomerAddressXML method build the Customer section of the
   * XML document. It will build a link, called AddressLink, to the
   * Addresses the customer is currently associated with.
   */
  private static Document buildCustomerAddressXML(ResultSet _customerAddressRS) 
                                                  throws Exception {
    Document xmlDoc = new DocumentImpl();

    /* Creating the root element */
    Element rootElement = xmlDoc.createElement("CUSTOMERADDRESS");
    Element customers = xmlDoc.createElement("CUSTOMERS");
    Element addresses = xmlDoc.createElement("ADDRESSES");

    xmlDoc.appendChild(rootElement);
    rootElement.appendChild(customers);
    rootElement.appendChild(addresses);

    /* Declaring the different Elements found within a customer record */
    Element customer = null;
    Element addressLinks = null;
    Element addressLink = null;

    /* Initializing customer id holders */
    String currentCustomerId = "";
    String holderCustomerId = "";

    /* Cycling through all of the records within the resultset */
    while (_customerAddressRS.next()) {

      /* Getting the customer id of the current record being looked at */
      currentCustomerId = _customerAddressRS.getString("customerid");

      if (!(currentCustomerId.equals(holderCustomerId))) {

        holderCustomerId = new String(currentCustomerId);

        /* Initialize the different elements found within an invoice record */
        customer = xmlDoc.createElement("CUSTOMER");
        addressLinks = xmlDoc.createElement("ADDRESSLINKS");
        addressLink = xmlDoc.createElement("ADDRESSLINK");

        /* Setting up my primary key for my customer */
        customer.setAttribute("customerid", 
                              _customerAddressRS.getString("customerid"));

        /* Adding my different elements to the customers header */
        customer.appendChild(buildDBElement(xmlDoc, "FIRSTNAME", 
                              _customerAddressRS.getString("customerfirstname")));
        customer.appendChild(buildDBElement(xmlDoc, "LASTNAME", 
                               _customerAddressRS.getString("customerlastname")));

        /* Appending my addresslinks element */
        customer.appendChild(addressLinks);
      } 

      /* Building my address link data */
      addressLink.setAttribute("addressid", 
                               _customerAddressRS.getString("addressid"));

      /* Appending everything together */
      addressLinks.appendChild(addressLink);

      addressLink = xmlDoc.createElement("ADDRESSLINK");

      /* Builds the actual address information */
      buildAddressesXML(_customerAddressRS, addresses, xmlDoc);

      customer.appendChild(addressLinks);
      customers.appendChild(customer);
    } 

    return xmlDoc;
  } 

  /*
   * The buildAddressesXML will build the Addresses section of the
   * CustomerAddress XML document. The method uses XPath to see if the address
   * being passed in already exists. If the address exists nothing further
   * is done with the Addresses element. If the address does not exist, a new
   * Address element is added as a child to the Addresses element.
   */
  private static void buildAddressesXML(ResultSet _customerAddressRS, 
                                        Element _addresses, 
                                        Document _xmlDoc) throws Exception {
    StringBuffer queryString = 
              new StringBuffer("/CUSTOMERADDRESS/ADDRESSES/ADDRESS[@addressid='");
    queryString.append(_customerAddressRS.getString("addressid"));
    queryString.append("']");


    /*
     * Use XPath to see if the   an address with the target address id we are
     * Looking for, already exists as part of the Addresses element.
     */
    Node queryResult = XPathAPI.selectSingleNode(_xmlDoc, 
            queryString.toString());

    /*
     * If a match is not found, add the address as a new element
     */
    if (queryResult == null) {
      Element address = _xmlDoc.createElement("ADDRESS");
      address.setAttribute("addressid", 
                           _customerAddressRS.getString("addressid"));

      address.appendChild(buildDBElement(_xmlDoc, "ADDRESS1", 
                                    _customerAddressRS.getString("address1")));
      address.appendChild(buildDBElement(_xmlDoc, "ADDRESS2", 
                                    _customerAddressRS.getString("address2")));
      address.appendChild(buildDBElement(_xmlDoc, "CITY", 
                                    _customerAddressRS.getString("city")));
      address.appendChild(buildDBElement(_xmlDoc, "STATE", 
                                    _customerAddressRS.getString("stateprov")));
      address.appendChild(buildDBElement(_xmlDoc, "ZIP", 
                                    _customerAddressRS.getString("postalcode")));
      address.appendChild(buildDBElement(_xmlDoc, "ADDRESSTYPE", 
                                    _customerAddressRS.getString("addresstype")));

      _addresses.appendChild(address);
    } 
  } 

  /*
   * The printDOM method below will write the contents of the xml document
   * passed into it out to the a file. The method will that the xml document
   * will be written out is defined by the File object passed into it.
   */
  private static void printDOM(Document _xmlDoc, 
                               File _outputFile) throws Exception {
    OutputFormat outputFormat = new OutputFormat("XML", "UTF-8", true);
    FileWriter fileWriter = new FileWriter(_outputFile);

    XMLSerializer xmlSerializer = new XMLSerializer(fileWriter, 
                                                    outputFormat);
    xmlSerializer.asDOMSerializer();

    xmlSerializer.serialize(_xmlDoc.getDocumentElement());
  } 

  /*
   * The buildDBElement will add a text node onto an element and return it back to
   * the method that calls it. This is simply a helper method that makes it easier
   * to add elements to another element.
   */
  private static Element buildDBElement(Document _xmlDoc, String _elementName, 
                                        String _elementValue) throws Exception {

    Element item = _xmlDoc.createElement(_elementName);
    item.appendChild(_xmlDoc.createTextNode(_elementValue));

    return item;
  } 
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -