2011-07-14 58 views
1

我寫了一個簡單的程序,它獲取一個字符串並將其轉換爲一個xml文檔,但它不顯示內容的價值,我將它設置爲顯示null!java中xml文檔的問題

import org.w3c.dom.Document; 
import org.w3c.dom.Element; 


    public class Server { 

     /** 
     * @param args 
     */ 
     public static void main(String[] args) { 
      Server server=new Server(); 
      Document dc=server.stringToDocument("f0"); 
      System.out.println(dc.getTextContent()); 

     } 
     public org.w3c.dom.Document stringToDocument(String order) 
     { 
      org.w3c.dom.Document result=null; 
      DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); 
      try{ 
      DocumentBuilder db=dbf.newDocumentBuilder(); 
      result=db.newDocument(); 
      Element el=result.createElement("ORDER"); 
      el.setTextContent(order); 
      } 
      catch (Exception e) { 
       System.out.println("DB in line 1418 exception"); 
      } 



      return result; 
     } 

    } 

回答

1

您需要將元素添加到文檔中,以使其與文檔相關聯。嘗試添加該行:

result.appendChild(el); 

有關更多信息,請參閱documentation

+0

我這樣做,但沒有改變accures ..其他ideaaaa? – sahera

0

您需要將行添加:

result.appendChild(el); 

到stringToDocument方法。

爲了讓XML字符串打印您可以使用下面的方法:

public String documentToString(Document doc) { 
    try { 
     Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
     transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 

     StreamResult result = new StreamResult(new StringWriter()); 
     DOMSource source = new DOMSource(doc); 
     transformer.transform(source, result); 

     String xmlString = result.getWriter().toString(); 
     return xmlString; 
    } catch (Exception e) { 
     return null; 
    } 
} 
+0

非常感謝您的答案..那很好 – sahera