2012-10-29 24 views
2

這是我的情況。將字符串轉換爲XMLDocument不會創建文本節點

我有一個包含XML數據的字符串:

<tag> 
    <anotherTag> data </anotherTag> 
</tag> 

我把這個字符串和我運行它通過這個代碼,將其轉換爲一個文件:

try { 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    return builder.parse(new InputSource(new StringReader(sXMLString))); 
} 
catch (Exception e) { 
    // Parser with specified options can't be built 
    ceLogger.logError("Unable to build a new XML Document from string provided:\t" + e.getMessage()); 
    return null; 
} 

生成的XML幾乎是完美的。它缺少數據和但是看起來像這樣:

<tag> 
    <anotherTag /> 
</tag> 

我如何可以複製在文本上創建一個XML文檔時,爲什麼它刪除擺在首位的文本?

編輯: 實際問題最終是沿着此線的東西: 同時,通過與我自己的函數這一行的XML結構分析有:

if (curChild.getNodeType()==Node.ELEMENT_NODE) 
    sResult.append(XMLToString((Element)children.item(i),attribute_mask)); 

但是,沒有這樣的邏輯存在TEXT節點,所以它們被簡單地忽略。

回答

5

您的代碼是正確的。我能做的唯一的猜測就是你輸出的代碼不正確。我測試你的代碼,並使用下面的方法來輸出,並用文本節點正確顯示XML:

public static void outputXML(Document dom) throws TransformerException 
{ 
    Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
    transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 

    //initialize StreamResult with File object to save to file 
    StreamResult result = new StreamResult(new StringWriter()); 
    DOMSource source = new DOMSource(dom); 
    transformer.transform(source, result); 

    String xmlString = result.getWriter().toString(); 
    System.out.println(xmlString); 
} 

產量爲:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<tag> <anotherTag> data </anotherTag> 
</tag> 
+0

在我的問題,輸入是一個帶有有效XML的字符串和我想要的輸出是一個具有正確XML結構的Document對象。你的代碼需要一個Document並生成一個字符串 – RGroppa

+0

正確,但是當你返回builder.parse(...)時你得到一個Document對象。我只是將這個Document對象傳遞給我上面編寫的outputXML方法來驗證Document實際上是否具有適當的XML結構。我認爲你寫出來輸出XML文檔的方法可能是錯誤的地方,而不是你要返回的Document數據結構。你可能會發布你如何輸出你的Document對象來驗證生成的XML文檔嗎? – smaccoun

+0

你是對的先生。我用來翻譯這個函數無法捕獲文本節點,這就是爲什麼當我嘗試查看它並且通過我的代碼處理它時,它沒有顯示出來。 – RGroppa