zfluo(云淡风清):
w3c.dom
jaxp

解决方案 »

  1.   

    Document doc
    doc.toString()试一下
      

  2.   

    /**
         * 将DOM的Document对象写入文件。
         * @param name 文件名称。
         * @param document DOM的Document对象。
         * @return 成功返回0
         * @throws java.io.IOException 写文件时出错。
         */
        public final static synchronized long writeXmlFile( java.lang.String name,
                                                            org.w3c.dom.Document document )
                                                    throws Exception
        {
            DOMSource doms = new DOMSource( document );
            File file = new File( name );
            StreamResult result = new StreamResult( file );
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            Properties properties = transformer.getOutputProperties();
            properties.setProperty( OutputKeys.ENCODING, "GB2312" );
            properties.setProperty( OutputKeys.METHOD, "xml" );
            properties.setProperty( OutputKeys.INDENT, "yes" );
            transformer.setOutputProperties( properties );
            transformer.transform( doms, result );        return 0;
        }
      

  3.   

    以上是使用Xalan的XSLT方式
    下面是JDOM的
        /**
         * 将JDOM的XMLDocument对象写入文件。
         * @param name 文件名称。
         * @param document JDOM的XMLDocument对象。
         * @return 成功返回0
         * @throws java.io.IOException 写文件时出错。
         */
        public final static synchronized long writeXmlFile( java.lang.String name,
                                                            org.jdom.Document document )
                                                    throws Exception
        {
            org.jdom.output.XMLOutputter xmlOut;
            document.setDocType( null ); // 不产生DocType PI
            xmlOut = new org.jdom.output.XMLOutputter( "    ", true, "GB2312" );
            xmlOut.setTextNormalize( true );        FileOutputStream out = new FileOutputStream( name );
            xmlOut.output( document, out );
            out.close();        return 0;
        }
      

  4.   

    Parser.jar中的xmlDocument方式
        /**
         * 将JAXP的XmlDocument对象写入文件。
         * @param name 存储的文件名称。
         * @param xmlDocument JAXP的XmlDocument对象。
         * @return 成功返回0。
         * @throws java.io.FileNotFoundException
         * @throws java.io.IOException
         */   public final static synchronized long writeXmlFile( java.lang.String name,com.sun.xml.tree.XmlDocument xmlDocument )
                         throws Exception
       {
           xmlDocument.trimToSize();
        
           // 输出到文件
           FileOutputStream out = new FileOutputStream( name );
           OutputStreamWriter writer = new OutputStreamWriter( out );
           xmlDocument.write( writer, "GB2312" );
           writer.close();
           out.close();
        
           return 0;
        }
    ECS
        /**
         * 将ECS的XMLDocument对象写入文件。
         * @param name 文件名称。
         * @param document ECS的XMLDocument对象。
         * @return 成功返回0
         * @throws Exception 写文件时出错。
         */
        public final static synchronized long writeXmlFile( java.lang.String name,
                                                            XMLDocument document )
                                                    throws Exception
        {
            // 输出到XML文件
            FileOutputStream out = new FileOutputStream( name );
            document.setCodeset( DatastorageConst.XML_FILE_ENCODING );
            document.output( out );
            out.close();        return 0;
        }
      

  5.   


    王文友不错,本帖可以收入精华了哦:)jdk1.4内置了jaxp,所以你用最后一个方法。
      

  6.   

    呵呵,不是啊,这个问题问的人比较多,我的本意是要把它提交为FAQ,省得大家都重复劳动:)
    不过xmlDocument是已经快废弃的了,JAXP新版本好像把Xalan的XSLT集成进去了,所以第一种方法也可用。
      

  7.   

    暂时我找不到比较直接的方法,先给你这个吧:)
    呵呵,其实你如果不对Document进行处理的话,还不如把它当做普通文本文件读进来呢
                DOMSource doms = new DOMSource( document );
                Writer out = new StringWriter();
                StreamResult result = new StreamResult( out );
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                // 如不关心输出格式,可省略以下几行
                Properties properties = transformer.getOutputProperties();
                properties.setProperty( OutputKeys.ENCODING, "GB2312" );
                properties.setProperty( OutputKeys.METHOD, "xml" );
                properties.setProperty( OutputKeys.INDENT, "yes" );
                transformer.setOutputProperties( properties );            transformer.transform( doms, result );
                System.out.println( out.toString() );
      

  8.   

    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    import javax.xml.parsers.*; 
    import javax.xml.transform.*; 
    import javax.xml.transform.dom.DOMSource; 
    import javax.xml.transform.stream.StreamResult; 
    import org.xml.sax.SAXException;
    import org.w3c.dom.*;
    import javax.xml.transform.dom.DOMSource;
    import java.io.*;
    import java.io.IOException;
    import java.util.Properties;public class XMLTest extends JApplet {
    String str;

    public void init()
    {
    str="hello";
        try 
        {
          DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); 
          factory.setNamespaceAware(true);
          DocumentBuilder db = factory.newDocumentBuilder();
          Document m_dDoc = db.newDocument();      m_dDoc=db.newDocument();
          
          Element eRoot=m_dDoc.createElement("first");
          m_dDoc.appendChild(eRoot);
          Element   e1=m_dDoc.createElement("second");
          Text tx;
          tx=m_dDoc.createTextNode("hello");
          e1.appendChild(tx);
          eRoot.appendChild(e1);                   DOMSource doms = new DOMSource( m_dDoc);
                Writer out = new StringWriter();
                StreamResult result = new StreamResult( out );
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
      
                transformer.transform( doms, result );
                System.out.println( out.toString() );             
        
        }
        catch (FactoryConfigurationError e) { 
          System.out.println("Could not locate a factory class"); 
        }
        catch (ParserConfigurationException e) { 
          System.out.println("Could not locate a JAXP parser"); 
        }
        
       
        catch (TransformerConfigurationException e) { 
          System.out.println("This DOM does not support transforms."); 
        } 
        catch (TransformerException e) { 
          System.out.println("Transform failed."); 
        }
    } public void paint(Graphics g) {

    g.drawString(str, 50, 60 );
    }
    }
      

  9.   

    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    import javax.xml.parsers.*; 
    import javax.xml.transform.*; 
    import javax.xml.transform.dom.DOMSource; 
    import javax.xml.transform.stream.StreamResult; 
    import org.xml.sax.SAXException;
    import org.w3c.dom.*;
    import javax.xml.transform.dom.DOMSource;
    import java.io.*;
    import java.io.IOException;
    import java.util.Properties;public class XMLTest extends JApplet {
    String str;

    public void init()
    {
    str="hello";
        try 
        {
          DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); 
          factory.setNamespaceAware(true);
          DocumentBuilder db = factory.newDocumentBuilder();
          Document m_dDoc = db.newDocument();      m_dDoc=db.newDocument();
          
          Element eRoot=m_dDoc.createElement("first");
          m_dDoc.appendChild(eRoot);
          Element   e1=m_dDoc.createElement("second");
          Text tx;
          tx=m_dDoc.createTextNode("hello");
          e1.appendChild(tx);
          eRoot.appendChild(e1);                   DOMSource doms = new DOMSource( m_dDoc);
                Writer out = new StringWriter();
                StreamResult result = new StreamResult( out );
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
      
                transformer.transform( doms, result );
                System.out.println( out.toString() );             
        
        }
        catch (FactoryConfigurationError e) { 
          System.out.println("Could not locate a factory class"); 
        }
        catch (ParserConfigurationException e) { 
          System.out.println("Could not locate a JAXP parser"); 
        }
        
       
        catch (TransformerConfigurationException e) { 
          System.out.println("This DOM does not support transforms."); 
        } 
        catch (TransformerException e) { 
          System.out.println("Transform failed."); 
        }
    } public void paint(Graphics g) {

    g.drawString(str, 50, 60 );
    }
    }
      

  10.   

    wangwenyou(王文友) :大虾,我现在怀疑我的DOM对象是否建立正确了
    再次麻烦您了!
      

  11.   

    呵呵,客气了,从程序上看,Document的建立没有问题,抛什么异常了?
      

  12.   

    使用ECS吧
        // ECS ecs.jar    import org.apache.ecs.xml.XMLDocument;
        import org.apache.ecs.xml.XML;
       /**
        * 建立ECS的XMLDocument对象。
        */
        private XMLDocument createXMLDocument()
        {
            XMLDocument document;
            // 建立一个ECS的文档对象,指定XML版本为1.0,编码为GB2312
            document = new XMLDocument(1.0,false,"GB2312");
            // 建立根节点
            document.addElement(new XML("Root"));        // 建立节点树
            XML node = new XML("RecordSet");
            XML field;        field = new XML("Name");
            field.addElement("MyName");
            node.addElement(field);        field = new XML("Age");
            field.addElement("20");
            node.addElement(field);         ......
              
            // 将节点加入文档对象容器
            document.addElement(node);
            return document;
        }
        上面的函数将建立一个如下的XML文件:
        <?xml version="1.0" encoding="GB2312"?>    <Root>        <RecordSet>                 <Name>MyName</Name>            <Age>20</Age>        </RecordSet>    </Root>
      

  13.   

    解决了
    import javax.xml.parsers.*;import javax.xml.transform.*;import javax.xml.transform.stream.*;import javax.xml.transform.dom.DOMSource;import java.io.*;import org.w3c.dom.*;public class XmlString{ public static void main(String[] args) throws Exception { DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance(); DocumentBuilder db = docFac.newDocumentBuilder(); Document doc = db.parse("books.xml"); TransformerFactory tfac = TransformerFactory.newInstance(); StringWriter strWtr = new StringWriter(); StreamResult strResult = new StreamResult(strWtr); Transformer trans = tfac.newTransformer(); trans.transform(new DOMSource(doc.getDocumentElement()), strResult); System.out.println(strResult.getWriter().toString()); } // main}
      

  14.   

    http://www.cn-java.com/target/news.php?news_id=1583
      

  15.   

    你尝试使用JDOM的XMLOutter:代码如下
             XMLOutputter output=new XMLOutputter();
    output.setEncoding("GB2312");
    String XMLString=output.outputString(Document的实例);
      

  16.   


    我的意思就是用javax.xml.transform.*的方法转换。
      

  17.   

    System.out.print(root.toString());
    注意,不要print(document).
      

  18.   

    also use
    ((XMLDocument)doc).write( your want stream)
      

  19.   

    你是用Java解析器还是别的
    Java:
    1.    Transformer transformer =
                TransformerFactory.newInstance().newTransformer();
        StringWriter sw = new StringWriter();
        transformer.transform(
                new DOMSource(node),new StreamResult(sw));
        String s = sw.toString();
    2.如果是Node节点(不是Document),可以直接用node.toString();