c# - How to return a subset of XElements inside parent XElement -
if have xml such following:
<validationresults> <validationresult> <scheme>scheme a</scheme> </validationresult> <validationresult> <scheme>scheme b</scheme> </validationresult>
i want query using linq xml
return:
<validationresults> <validationresult> <scheme>scheme a</scheme> </validationresult> </validationresults>
if this:
....element("validationresults").elements("validaitonresult") .where(x => x.element("scheme").value == "scheme a");
i return only:
<validationresult> <scheme>scheme a</scheme> </validationresult>
then creating parent again , adding children it, not seem correct:
var parentelement = new xelement("validationresults"); var childelements = //get above parentelement.add(childelements);
how return queried subset of elements inside it's original parent?
your current approach seems simplest 1 me, although done in single statement as:
var element = new xelement("validationresults", doc.element("validationresults") .elements("validationresult") .where(x => x.element("scheme").value == "scheme a")));
assuming don't want modify existing document, either have come new "root" validation results element or need clone existing 1 , remove you're not interested in. copying in elements want seems simpler pruning out don't want.
of course, avoid duplication of string literal pretty - extract constant somewhere, can make sure you're creating new element same name old one.
Comments
Post a Comment