在與其他產品或服務Web services做溝通時,常常都會使用XML做資料交換的格式
最近遇到一個很特殊的案例,對方希望在傳過去的XML內容包兩層,第二層外面Tag要加上" XML內容 "]]>
XML文字內容只要被包在裡面的,XML解析器在解析時就不會去解析裡面的內容,這樣的文字稱為Character Data Section,簡稱CData Section。
以下是範例是說明如何使用C# 建立 CDATA Section
使用 XMLDocument
string myXml = @""; XmlDocument doc1 = new XmlDocument(); doc1.LoadXml(myXml); XmlNode target = doc1.SelectSingleNode("WorkingSet/Data"); if (target != null) target.AppendChild(doc1.CreateCDataSection(" Hello "));
使用 XDocument
XDocument doc = XDocument.Parse(myXml, LoadOptions.SetLineInfo);
XElement dataNode = doc.Descendants("Data").First();
dataNode.Add(new XCData("
Hello
Console.WriteLine(doc.ToString());