C#에서 <![CDATA[ ... ]]>
안의 내용을 추출하려면 System.Xml
네임스페이스의 XmlDocument
또는 XDocument
를 사용할 수 있습니다.
✅ 방법 1: XmlDocument
를 사용하는 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Xml; class Program { static void Main() { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <Receipt> <CONTENT> <![CDATA[<head xmlns:js=""javascript:code""> <meta http-equiv=""X-UA-Compatible"" content=""IE=Edge;"" /> <meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" /> <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" /> <link rel=""preconnect"" href=""https://fonts.googleapis.com"" /> <link rel=""preconnect"" href=""https://fonts.gstatic.com"" /> <link href=""https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;700;family=Noto+Sans:wght@700;display=swap"" rel=""stylesheet"" /> </head>]]> </CONTENT> </Receipt>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); var cdataContent = doc.SelectSingleNode("//CONTENT").InnerText; Console.WriteLine(cdataContent); } } |
✅ 방법 2: XDocument
(LINQ to XML) 방식
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Xml.Linq; class Program { static void Main() { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <Receipt> <CONTENT><![CDATA[<head>...</head>]]></CONTENT> </Receipt>"; XDocument doc = XDocument.Parse(xml); string cdata = doc.Root.Element("CONTENT").Value; Console.WriteLine(cdata); } } |
✅ 결과
출력은 CDATA 내부의 HTML:
1 2 3 4 5 6 7 |
<head xmlns:js="javascript:code"> <meta http-equiv="X-UA-Compatible" content="IE=Edge;" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> ... </head> |