2009-08-01 82 views
6

我想寫包含空格字符,如newlinetab到一個XML文件,所以我用如何在生成XML時保留CDATA中的換行符?

Element element = xmldoc.createElement("TestElement"); 
element.appendChild(xmldoc.createCDATASection(somestring)); 

但是當我在使用

Node vs = xmldoc.getElementsByTagName("TestElement").item(0); 
String x = vs.getFirstChild().getNodeValue(); 

讀這回我得到一個字符串的一些文字沒有換行符了。
當我直接看到磁盤上的XML,新行似乎保留。所以在xml文件中讀取時會發生問題。

我該如何保留換行符?

謝謝!

+2

你能發佈一個更完整的代碼示例嗎? – skaffman 2009-08-01 16:03:10

+0

它是一個元素。我會盡快發佈更多代碼。 – clamp 2009-08-01 16:06:26

+0

當你得到'x'的值時,它相當於'somestring'減去換行符? – akf 2009-08-01 16:19:22

回答

5

我不不知道如何解析和編寫文檔,但以下是基於您的文檔的增強代碼示例:

// creating the document in-memory               
Document xmldoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); 

Element element = xmldoc.createElement("TestElement");          
xmldoc.appendChild(element);                
element.appendChild(xmldoc.createCDATASection("first line\nsecond line\n"));    

// serializing the xml to a string               
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();    

DOMImplementationLS impl =                 
    (DOMImplementationLS)registry.getDOMImplementation("LS");        

LSSerializer writer = impl.createLSSerializer();           
String str = writer.writeToString(xmldoc);             

// printing the xml for verification of whitespace in cdata        
System.out.println("--- XML ---");               
System.out.println(str);                 

// de-serializing the xml from the string             
final Charset charset = Charset.forName("utf-16");           
final ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes(charset));  
Document xmldoc2 = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input); 

Node vs = xmldoc2.getElementsByTagName("TestElement").item(0);       
final Node child = vs.getFirstChild();              
String x = child.getNodeValue();               

// print the value, yay!                 
System.out.println("--- Node Text ---");             
System.out.println(x);                  

使用LSSerializer的序列化是W3C的方法(see here)。輸出如預期的那樣,使用行分隔符:

--- XML --- 
<?xml version="1.0" encoding="UTF-16"?> 
<TestElement><![CDATA[first line 
second line ]]></TestElement> 
--- Node Text --- 
first line 
second line 
0

編輯:切斷所有不相干的東西

我很好奇,想知道你正在使用的DOM實現,因爲它不反映一個的默認行爲在一對夫婦的JVM我已經試過(他們用Xerces impl發貨)。我也對你的文檔有哪些換行符有興趣。

我不確定CDATA是否應該保留空格是給定的。我懷疑涉及的因素很多。不要DTD /模式影響如何處理空白?

您可以嘗試使用xml:space =「preserve」屬性。

2

您需要使用node.getNodeType()檢查每個節點的類型。如果類型是CDATA_SECTION_NODE,則需要將CDATA衛兵連接到node.getNodeValue。

2

您不一定非得使用CDATA來保留空格字符。 XML specification指定如何編碼這些字符。

因此,舉例來說,如果你有一個元素將包含新的空間價值,你應該

&#xA; 

回車進行編碼:

&#xD; 

如此反覆

0

xml:space ='preserve'是不是。這僅適用於「所有空白」節點。也就是說,如果你想要的空白節點在

<this xml:space='preserve'> <has/> 
<whitespace/> 
</this> 

但看到那些空白節點只有空白。

我一直在努力讓Xerces生成允許分離CDATA內容的事件。我還沒有解決方案。

相關問題