整理了一个文档,会对你有帮助//:xml-解析xml字符串.txtimport java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Reader;
import java.io.StringReader;import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
//import com.ibm.xml.parsers.*;
import com.sun.xml.parser.Parser;
import com.sun.xml.tree.XmlDocumentBuilder;/**
 * A sample DOM writer. This sample program illustrates how to
 * traverse a DOM tree.
 */public class parseString
{
  public void parseAndPrint(InputSource xmlSource)
  {
    Document doc = null;    try
    {
     //sun的解析器. http://java.sun.com/xml
     XmlDocumentBuilder builder = new XmlDocumentBuilder();
      Parser parser = new com.sun.xml.parser.Parser();
      parser.setDocumentHandler(builder);
      builder.setParser(parser);
      builder.setDisableNamespaces(false);
      parser.parse(xmlSource);
      doc = builder.getDocument();
    
     /*
     //IBM的XML4j解析器。http://www.alphaworks.ibm.com 
      DOMParser parser = new DOMParser();
      parser.parse(xmlSource);
      doc = parser.getDocument();
      */
    }
    catch (Exception e)
    {
      System.err.println("Sorry, an error occurred: " + e);
    }    // We've parsed the document now, so let's print it.      if (doc != null)
      printDOMTree(doc);
  }  /** Prints the specified node, recursively. */
  public void printDOMTree(Node node) 
  {
    int type = node.getNodeType();
    switch (type)
    {
      // print the document element
      case Node.DOCUMENT_NODE: 
        {
          System.out.println("<?xml version=\"1.0\" ?>");
          printDOMTree(((Document)node).getDocumentElement());
          break;
        }        // print element with attributes
      case Node.ELEMENT_NODE: 
        {
          System.out.print("<");
          System.out.print(node.getNodeName());
          NamedNodeMap attrs = node.getAttributes();
          for (int i = 0; i < attrs.getLength(); i++)
          {
            Node attr = attrs.item(i);
            System.out.print(" " + attr.getNodeName() + 
                             "=\"" + attr.getNodeValue() + 
                             "\"");
          }
          System.out.println(">");          NodeList children = node.getChildNodes();
          if (children != null)
          {
            int len = children.getLength();
            for (int i = 0; i < len; i++)
              printDOMTree(children.item(i));
          }          break;
        }        // handle entity reference nodes
      case Node.ENTITY_REFERENCE_NODE: 
        {
          System.out.print("&");
          System.out.print(node.getNodeName());
          System.out.print(";");
          break;
        }        // print cdata sections
      case Node.CDATA_SECTION_NODE: 
        {
          System.out.print("<![CDATA[");
          System.out.print(node.getNodeValue());
          System.out.print("]]>");
          break;
        }        // print text
      case Node.TEXT_NODE: 
        {
          System.out.print(node.getNodeValue());
          break;
        }        // print processing instruction
      case Node.PROCESSING_INSTRUCTION_NODE: 
        {
          System.out.print("<?");
          System.out.print(node.getNodeName());
          String data = node.getNodeValue();
          {
            System.out.print(" ");
            System.out.print(data);
          }
          System.out.print("?>");
          break;
        }
    }    if (type == Node.ELEMENT_NODE)
    {
      System.out.println();
      System.out.print("</");
      System.out.print(node.getNodeName());
      System.out.print('>');
    }
  } // printDOMTree(Node)  /** Main program entry point. */
  public static void main(String argv[]) 
  {
    parseString ps = new parseString();
    //这里输入xml字符串,获得xml字符串的方法很多
    StringReader sr = new StringReader("<?xml version=\"1.0\"?><a>Alpha<b>Bravo</b><c>Charlie</c></a>");
    InputSource iSrc = new InputSource(sr);
    ps.parseAndPrint(iSrc);
  }
}

解决方案 »

  1.   

    to tangshancheng(98007):
    要实现打印功能,需要这么复杂吗??/**
     * <p>Title: </p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2002</p>
     * <p>Company: </p>
     * @author unascribed
     * @version 1.0
     */
    import org.w3c.dom.*;
    import org.apache.xerces.dom.*;
    import org.apache.xml.serialize.*;
    import org.jdom.input.SAXBuilder;
    import org.apache.xerces.parsers.*;
    import java.io.*;public class TestXML {    public TestXML() {
        }
        public static Document buildXMLDoc(){
            Document xmlDoc = new DocumentImpl();
            Element rootElement = xmlDoc.createElement("CALL");
            xmlDoc.appendChild(rootElement);        Element method = xmlDoc.createElement("METHOD");
            method.setAttribute("name","modifyDataChose");
            Element param1 = xmlDoc.createElement("TemplateID");
            param1.appendChild(xmlDoc.createTextNode("1010"));
            method.appendChild(param1);
            Element param2 = xmlDoc.createElement("Condition");
            param2.appendChild(xmlDoc.createTextNode("1=1"));
            method.appendChild(param2);
            rootElement.appendChild(method);
            return xmlDoc;
        }
        public static void printDOM(Document xmlDoc,Writer writer) throws IOException{
            OutputFormat format = new OutputFormat("XML","UTF-8",true);
            XMLSerializer xmlSerializer = new XMLSerializer(writer,format);
            xmlSerializer.asDOMSerializer();
            xmlSerializer.serialize(xmlDoc.getDocumentElement());
        }
        public static void retriveXMLDom(Reader reader) throws Exception{
            SAXBuilder sb = new SAXBuilder();
            org.jdom.Document doc = sb.build(reader);
            String str = doc.getRootElement().getChild("METHOD").getChild("Template").getText();
            //String str = doc.getRootElement().getChild("METHOD").getChild("TemplateID").getText();
            System.out.println(""+str);
        }
        public static void main(String[] args) throws Exception{
            Document doc = buildXMLDoc();        ByteArrayOutputStream bos = new ByteArrayOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
            printDOM(doc,writer);        System.out.println("-------------------------");
            retriveXMLDom(new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bos.toByteArray()))));
        }
    }
      

  2.   

    to tangshancheng(98007):
    要实现打印功能,需要这么复杂吗??演示而已。呵呵