C# XML 文件中的空格值問題
運行環境:Window7 64bit,.NetFramework4.61,C# 6.0; 編者:烏龍哈里 2017-02-15
近期正在寫我的簡易標記文件格式的程序,用 xml 文件來當配置文件,結果發現一個事,能把空格寫進 xml 文件,但讀取的時候發現是空值,並不是空格值。
以下做實驗:
string path = @"d:\test\1.xml";
XElement xe = new XElement("root",new XElement("a"," "));
Console.WriteLine(xe.ToString());
xe.Save(path);
XElement xt = XElement.Load(path);
string s = xt.Element("a").Value;
Console.WriteLine($"12{s}34");
Console.ReadKey();
/*結果:
<root>
<a> </a>
</root>
1234
*/
讀取時,空格沒有了。查了資料才知道是 xml 文件格式的規定問題。
解決辦法:給元素加上屬性 xml:space="preserve"。本來想用 XAttribute 來程序寫入,出現錯誤是 不能帶 : 符號,沒則,只有手工添加。添加后運行:
string s = xt.Element("a").Value;
Console.WriteLine($"12{s}34");
/*結果:
<root xml:space="preserve">
<a> </a>
</root>
12 34
*/
