Search code examples
c#xmllinq-to-xmlxelementxmlnode

How to convert list of XElement to XDocument?


My work is to remove some nodes from an XML based upon certain conditions and then parse the changed XML to a string.

To do that:

I converted string(workingData)to Xdocument and then added a condition to select xelements (abc) which works fine.

Now I need help to replace existing xelements with the new xelement(abc) back in doc with the removed nodes.

PS: Ignore the hardcoded return "xx" that will be changed later to the converted xml.

 private string convertXML(string workingData, IEnumerable<string> fulfillerClaims)
            {
                XDocument doc = XDocument.Parse(workingData);
                IEnumerable<XElement> abc;
                foreach (XElement item in doc.Elements())
                {
                    abc = item.Elements().Where(x => x.Name.LocalName == "Entry").Select(x => x).Where(x => x.Attribute("Fulfiller") == null || fulfillerClaims.Contains(x.Attribute("Fulfiller").Value));
                }     


                return "xx";
            }

Solution

  • You could just remove the elements you don't want? I think this would work:

    foreach (XElement item in doc.Elements()) {
        item.Elements().Where(x => x.Name.LocalName != "Entry" && (x.Attribute("Fulfiller") != null && !fulfillerClaims.Contains(x.Attribute("Fulfiller").Value))).Remove();
    }
    

    Might want to check the conditional logic on this.. I didn't have any test data to work with...

    I did remove parts of it like this that just seemed to be wasting cycles:

    .Select(x => x)