Extracting data from CDATA using LINQ to XML
I have the following xml file开发者_开发问答 and I am trying to use linq to xml to get the Elements which are residing inside the CDATA section. Any suggestions please.
<?xml version = "1.0" encoding = "UTF-8"?>
<result final = "true" transaction-id="84WO" xmlns="http://cp.com/rules/client">
<client id = "CustName'>
<quoteback>
</client>
<report format = "CP XML">
<![CDATA[<?xml version="1.0" encoding = "UTF-8" standalone = "yes"?>
<personal_auto xmlns = "http://cp.com/rules/client">
<admin>
</admin>
<report>
</report>
</personal_auto>
]]>
</report> </result>
XElement XTemp = XElement.Load(YourXMLfile);
var queryCDATAXML = from element in XTemp.DescendantNodes()
where element.NodeType == System.Xml.XmlNodeType.CDATA
select element.Parent.Value.Trim();
This is standard LINQ functionality - see http://msdn.microsoft.com/en-us/library/system.xml.linq.xcdata.aspx
Could you please explain the problem in more detail if this doesn't solve it?
I was looking to do something slightly different - I'm embedding sql in xml using cdata in its own dedicated element named 'sql'
Just to clarify cdata content will be read transparently.
if you do
var cdataContent = sql.Value;
you get whatever string is in the
<![CDATA[..]]>
tag without having to instantiate a different node type on top of it or do anything fancy
so in the above case cdataContent would just be "..".
Linq to sql really is nice! I always expect there to be more messing about involved. Hats off to the guys who made that API.
精彩评论