Reputation: 155
I have searched around looking for ways to get at the CDATA section text area and found very luk warm solutions using linq. I need to extract the XML imbedded in the CDATA Section so I can pull out different pieces of info. I have the following XML:
<Envelope>
<Warehouse />
<Payload>
- <![CDATA[
<?xml version="1.0"?>
<ROOT>
<ORDERID>399798</ORDERID>
<PRODUCTNUMBER>00003997</PRODUCTNUMBER>
<DESCIPTION>Red Rider BB-Gun</DESCIPTION>
<STATUS>InStock</STATUS>
<LOCATION>Chicago</LOCATION>
</ROOT> ]]>
</Payload>
</Envelope>
So I would like if possible to do this by extracting the whole cdata section into an XDocument so I can use Linq to query. Also if I just wanted to pull out a single Element from the CData section. How can I do this? Using Linq?
I have tried using this Linq code below to give me back cdata section but can't do anything with it since it comes back as an IEnumerable. I'm probably missing something easy so I come to you the Linq wizards for some help.
Here's the code I mentioned:
var queryCDATAXML = from el in xdoc.DescendantNodes()
where el.NodeType == XmlNodeType.CDATA
select el.Parent.Value.Trim();
Is there a way to do a select new XDocument or XmlDocument like so:
//This doesn't compile.
var queryCDATAXML = from el in xdoc.DescendantNodes()
where el.NodeType == XmlNodeType.CDATA
select new XDocument()
{
el.Parent.Value.Trim();
}
If I am going about this all wrong or their is a better way to accomplish this I'm open for suggestions. :)
Thanks, DND
Code Update:
var queryCDATAXML = from el in xdoc.DescendantNodes()
where el.NodeType == XmlNodeType.CDATA
select el.Parent.Value.Trim();
var xdoc = XDocument.Parse(queryCDATAXML);
Generates this error: Argument '1': cannot convert from 'System.Collections.Generic.IEnumerable' to 'string'.
Upvotes: 3
Views: 11329
Reputation: 1
I resolved this case in this form:
XDocument xdoc = XDocument.Parse(vm.Xml);
XNamespace cbc = @"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
var list2 =
(from el in xdoc.Descendants(cbc + "Description")
select el).FirstOrDefault();
var queryCDATAXML = (from eel in list2.DescendantNodes()
select eel.Parent.Value.Trim()).FirstOrDefault();
I hope help them
Upvotes: 0
Reputation: 28718
Rather than new XDocument
, try XDocument.Parse
var queryCDATAXML = // get the value
var xdoc = XDocument.Parse(queryCDATAXML);
You're getting some Enumerable<string>
rather than string
, so you need to just get the single value.
var node = xdoc.DescendantNodes().Single(el => el.NodeType == XmlNodeType.CDATA);
var content = node.Parent.Value.Trim();
var xdoc = XDocument.Parse(content);
Upvotes: 11