import javax.xml.parsers.*;
import org.w3c.dom.*;public class DOMTest {  public static void main(String[] args) throws Exception {
    DOMTest dt = new DOMTest(args[0]);
  }  public DOMTest(String uri) throws Exception {
    DocumentBuilderFactory factory =
        DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(uri);
    displayTree(doc.getDocumentElement());
  }  protected void displayTree(Node node) {
    short nodeType = node.getNodeType();
    switch (nodeType) {
      case Node.ELEMENT_NODE:
        printElement((Element)node);
        break;
      case Node.TEXT_NODE:
        printText((Text)node);
        break;
      case Node.COMMENT_NODE:
        printComment((Comment)node);
        break;
      case Node.CDATA_SECTION_NODE:
        printCDATA((CDATASection)node);
        break;
      case Node.ENTITY_REFERENCE_NODE:
        printEntityReference((EntityReference)node);
        break;
      case Node.PROCESSING_INSTRUCTION_NODE:
        printProcessingInstruction(
            (ProcessingInstruction)node);
        break;
      default:
    }
  }  protected void printElement(Element node) {
    Node child;
    Attr attr;
    System.out.print("<" + node.getNodeName());
    NamedNodeMap attrs = node.getAttributes();
    int count = attrs.getLength();
    for (int i = 0; i < count; i++) {
      attr = (Attr)(attrs.item(i));
      System.out.print(" " + attr.getName() + "=\"" + attr.getValue() +
                       "\"");
    }
    System.out.print(">");
    NodeList children = node.getChildNodes();
    count = children.getLength();
    for (int i = 0; i < count; i++) {
      child = children.item(i);
      displayTree(child);
    }
    System.out.print("</" + node.getNodeName() + ">");
  }
  protected void printText(CharacterData node) {
    System.out.print(node.getData());
  }  protected void printComment(Comment node) {
    System.out.print("<!--" + node.getData() + "-->");
  }  protected void printCDATA(CDATASection node) {
    System.out.print("<![CDATA[" + node.getData() + "]]>");
  }  protected void printEntityReference(EntityReference node) {
    System.out.print("&" + node.getNodeName() + ";");
  }  protected void printProcessingInstruction(ProcessingInstruction node) {
    System.out.print("<?" + node.getTarget() + " " + node.getData() + "?>");
  }}通用的代码!!!
不过有人又要说我四处卖弄了
555555555啊啊啊.......

解决方案 »

  1.   

    import java.io.*;
    import java.text.*;
    import java.util.*;
    import org.jdom.*;
    import org.jdom.input.*;
    import org.jdom.output.*;/**
     * Provides the the ability to use simple XML property files. Each property is
     * in the form X.Y.Z, which would map to an XML snippet of:
     * 解析XML文档,将XML的所有数据存入一个HashMap中,节点之间以“.”分隔。
     * <pre>
     * &lt;X&gt;
     *     &lt;Y&gt;
     *         &lt;Z&gt;someValue&lt;/Z&gt;
     *     &lt;/Y&gt;
     * &lt;/X&gt;
     * </pre>
     *
     * The XML file is passed in to the constructor and must be readable and
     * writtable. Setting property values will automatically persist those value
     * to disk.
     * 
     */
    public class XMLProperties {    private File file;
        private Document doc;
        /**
         * Parsing the XML file every time we need a property is slow. Therefore,
         * we use a Map to cache property values that are accessed more than once.
         */
        private Map propertyCache = new HashMap();    /**
         * Creates a new XMLProperties object.
         *
         * @parm file String 完整的XML文件路径
         *
         */
        public XMLProperties(String file) {
            this.file = new File(file);
            try {
                SAXBuilder builder = new SAXBuilder();
                // Strip formatting
                DataUnformatFilter format = new DataUnformatFilter();
                builder.setXMLFilter(format);
                doc = builder.build(new File(file));
            }
            catch (Exception e) {
                System.err.println("Error creating XML parser in "
                    + "PropertyManager.java");
                e.printStackTrace();
            }
        }    /**
         * Returns the value of the specified property.
         *获得指定节点名的节点值
         * @param name the name of the property to get.
         * @return the value of the specified property.
         */
        public String getProperty(String name) {
            if (propertyCache.containsKey(name)) {
                return (String)propertyCache.get(name);
            }        String[] propName = parsePropertyName(name);
            // Search for this property by traversing down the XML heirarchy.
            Element element = doc.getRootElement();
            for (int i = 0; i < propName.length; i++) {
                element = element.getChild(propName[i]);
                if (element == null) {
                    // This node doesn't match this part of the property name which
                    // indicates this property doesn't exist so return null.
                    return null;
                }
            }
            // At this point, we found a matching property, so return its value.
            // Empty strings are returned as null.
            String value = element.getText();
            if ("".equals(value)) {
                return null;
            }
            else {
                // Add to cache so that getting property next time is fast.
                value = value.trim();
                propertyCache.put(name, value);
                return value;
            }
        }
      

  2.   

    /**
         * Return all children property names of a parent property as a String array,
         * or an empty array if the if there are no children. For example, given
         * the properties <tt>X.Y.A</tt>, <tt>X.Y.B</tt>, and <tt>X.Y.C</tt>, then
         * the child properties of <tt>X.Y</tt> are <tt>A</tt>, <tt>B</tt>, and
         * <tt>C</tt>.
         *获得指定父节点的所有子节点,返回String数组
         * @param parent the name of the parent property.
         * @return all child property values for the given parent.
         */
        public String [] getChildrenProperties(String parent) {
            String[] propName = parsePropertyName(parent);
            // Search for this property by traversing down the XML heirarchy.
            Element element = doc.getRootElement();
            for (int i = 0; i < propName.length; i++) {
                element = element.getChild(propName[i]);
                if (element == null) {
                    // This node doesn't match this part of the property name which
                    // indicates this property doesn't exist so return empty array.
                    return new String [] { };
                }
            }
            // We found matching property, return names of children.
            List children = element.getChildren();
            int childCount = children.size();
            String [] childrenNames = new String[childCount];
            for (int i=0; i<childCount; i++) {
                childrenNames[i] = ((Element)children.get(i)).getName();
            }
            return childrenNames;
        }    /**
         * Sets the value of the specified property. If the property doesn't
         * currently exist, it will be automatically created.
         *设置节点值
         * @param name the name of the property to set.
         * @param value the new value for the property.
         */
        public void setProperty(String name, String value) {
            // Set cache correctly with prop name and value.
            propertyCache.put(name, value);        String[] propName = parsePropertyName(name);
            // Search for this property by traversing down the XML heirarchy.
            Element element = doc.getRootElement();
            for (int i=0; i<propName.length; i++) {
                // If we don't find this part of the property in the XML heirarchy
                // we add it as a new node
                if (element.getChild(propName[i]) == null) {
                    element.addContent(new Element(propName[i]));
                }
                element = element.getChild(propName[i]);
            }
            // Set the value of the property in this node.
            element.setText(value);
            // write the XML properties to disk
            saveProperties();
        }    /**
         * Deletes the specified property.
         *删除指定的节点
         * @param name the property to delete.
         */
        public void deleteProperty(String name) {
            String[] propName = parsePropertyName(name);
            // Search for this property by traversing down the XML heirarchy.
            Element element = doc.getRootElement();
            for (int i=0; i<propName.length-1; i++) {
                element = element.getChild(propName[i]);
                // Can't find the property so return.
                if (element == null) {
                    return;
                }
            }
            // Found the correct element to remove, so remove it...
            element.removeChild(propName[propName.length-1]);
            // .. then write to disk.
            saveProperties();
        }
      

  3.   

    /**
         * Saves the properties to disk as an XML document. A temporary file is
         * used during the writing process for maximum safety.
         * 将修改的结果存入XML文件
         */
        private synchronized void saveProperties() {
            OutputStream out = null;
            boolean error = false;
            // Write data out to a temporary file first.
            File tempFile = null;
            try {
                tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
                // Use JDOM's XMLOutputter to do the writing and formatting. The
                // file should always come out pretty-printed.
                XMLOutputter outputter = new XMLOutputter("    ", true);
                out = new BufferedOutputStream(new FileOutputStream(tempFile));
                outputter.output(doc, out);
            }
            catch (Exception e) {
                e.printStackTrace();
                // There were errors so abort replacing the old property file.
                error = true;
            }
            finally {
                try {  out.close();  }
                catch (Exception e) {
                    e.printStackTrace();
                    error = true;
                }
            }
            // No errors occured, so we should be safe in replacing the old
            if (!error) {
                // Delete the old file so we can replace it.
                file.delete();
                // Rename the temp file. The delete and rename won't be an
                // automic operation, but we should be pretty safe in general.
                // At the very least, the temp file should remain in some form.
                tempFile.renameTo(file);
            }
        }    /**
         * Returns an array representation of the given Jive property. Jive
         * properties are always in the format "prop.name.is.this" which would be
         * represented as an array of four Strings.
         *解析节点名。以“.”分隔父节点和子节点
         * @param name the name of the Jive property.
         * @return an array representation of the given Jive property.
         */
        private String[] parsePropertyName(String name) {
            // Figure out the number of parts of the name (this becomes the size
            // of the resulting array).
            int size = 1;
            for (int i=0; i<name.length(); i++) {
                if (name.charAt(i) == '.') {
                    size++;
                }
            }
            String[] propName = new String[size];
            // Use a StringTokenizer to tokenize the property name.
            StringTokenizer tokenizer = new StringTokenizer(name, ".");
            int i = 0;
            while (tokenizer.hasMoreTokens()) {
                propName[i] = tokenizer.nextToken();
                i++;
            }
            return propName;
        }
        public static void main(String[] args) {
            XMLProperties xp = new XMLProperties("jive_config.xml");
            String p = xp.getProperty("skin.default.communityDescription");
            System.out.println("p==="+p);
        }
    }
      

  4.   

    有没有用dom4j来读取xml文件的,谢谢