2012-01-06 45 views
2

XML文檔,我使用下述代碼在C#創建一個XML:創建使用LINQ到XML在C#

 XDocument xDoc = new XDocument(new XDeclaration("1.0", "UTF-16","yes"), 
      new XElement("Parent", 
      from childItem in childItemList 
      select new XElement("Child", 
        new XElement("source",childItem.Source), 
        new XElement("target", childItem.Target) 
        ))); 

其做工精細,並如預期的那樣創建的文檔。但我想寫

childItem.Source 
    childItem.Target 

的屬性值和我用的是下面的代碼:

XDocument xDoc = new XDocument(new XDeclaration("1.0", "UTF-16","yes"), 
      new XElement("Parent", 
      from childItem in childItemList 
      select new XElement("Child", 
        (new XAttribute("value", childItem.Source))), 
       new XElement("target", 
       (new XAttribute("value",childItem.Target))) 
       ))); 

此代碼也能正常工作,但問題是我在

多行文本
childItem.Source 
    childItem.Target 

當同樣被寫爲一個節點的內文時,它可以正常工作,但是當它被寫爲屬性的值時,多行文本被轉換爲單行文本。我想保留XML文檔中的所有空格和換行符。任何幫助表示讚賞。

回答

0

在屬性中不能有換行符(CRLF)!換行總是從XElement類轉換爲十六進制文字,以便「安全」。我想這是爲了成爲HTTP(或其他網絡協議)符合 - 例如,在URI中不允許新行。您始終可以從您擁有的十六進制值中恢復您的CRLF。