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節點,所以它們被簡單地忽略。
在我的問題,輸入是一個帶有有效XML的字符串和我想要的輸出是一個具有正確XML結構的Document對象。你的代碼需要一個Document並生成一個字符串 – RGroppa
正確,但是當你返回builder.parse(...)時你得到一個Document對象。我只是將這個Document對象傳遞給我上面編寫的outputXML方法來驗證Document實際上是否具有適當的XML結構。我認爲你寫出來輸出XML文檔的方法可能是錯誤的地方,而不是你要返回的Document數據結構。你可能會發布你如何輸出你的Document對象來驗證生成的XML文檔嗎? – smaccoun
你是對的先生。我用來翻譯這個函數無法捕獲文本節點,這就是爲什麼當我嘗試查看它並且通過我的代碼處理它時,它沒有顯示出來。 – RGroppa