Steve Cardella
Steve Cardella

Reputation: 57

C# XDocument remove attributes not in a list

I'm querying a webservice in C# and it returns XML, which I've parsed into an XDocument. I remove an extraneous node that returns statistics about the service call and am left with something like this:

<xml>
   <element attr1="1" attr2="2" attr3="3" attr4="4" ... attrN="N" />
   <element attr1="a" attr2="b" attr3="c" ... attrN="N" />
   ...
   <element attr1="!" attr2="?" attr3=":" attr4="" ... attrN="N /> 
</xml>

I'm really only interested in retrieving attr2 and attr3, so I want to remove all the other attributes to wind up with this:

<xml>
   <element attr2="2" attr3="3" />
   <element attr2="b" attr3="c" />
   ...
   <element attr2="?" attr3=":" />
</xml>

However, here's the relevant bit of code I'm using and it is only removing attr1:

String[] WS_LookupFields = "attr2,attr3".Split(',');
var output = XDocument.Parse(WS_Output_Raw);
output.Descendants("system").Remove(); //removes query statistics
foreach (XAttribute attribute in output.Descendants("element").Attributes())
{
    if (!Array.Exists<String>(WS_LookupFields, fieldname => attribute.Name == fieldname)) attribute.Remove();
}

The problem is that the foreach only returns attr1 and not attr1 through attrN. Any suggestions?

Upvotes: 0

Views: 1509

Answers (5)

PinBack
PinBack

Reputation: 2564

Use this:

var WS_LookupFields = "attr2,attr3".Split(',').ToList();
var output = XDocument.Parse(WS_Output_Raw);
foreach (var loElement in output.Descendants("element"))
{
    //loElement.Attributes()
    //    .Where(item => !WS_LookupFields.Any(name => item.Name == name))
    //    .ToList()
    //    .ForEach(item => item.Remove());
    //UPDATE: Charles Mager
    loElement.Attributes()
        .Where(item => !WS_LookupFields.Any(name => item.Name == name))
        .Remove();
}

Or:

foreach (var loAttribute in output.Descendants("element").Attributes().ToList())
{
    if (!WS_LookupFields.Contains(loAttribute.Name.ToString()))
        loAttribute.Remove();
}

Upvotes: 2

Jeff Mercado
Jeff Mercado

Reputation: 134841

There are methods designed to remove xml content from the tree. You used the one for Elements already, use the one for attributes as well.

Build up a query to select the attributes you want to remove, then remove them.

var attrs = new HashSet<string>("attr2,attr3".Split(','));
foreach (var e in output.Descendants("element"))
    e.Attributes().Where(a => !attrs.Contains(a.Name.LocalName)).Remove();

// or simply
output.Descendants("element")
    .Attributes()
    .Where(a => !attrs.Contains(a.Name.LocalName))
    .Remove();

Upvotes: 2

Fabio
Fabio

Reputation: 32445

Just create new document with required attributes

var required = new HashSet<string> { "attr2", "attr3" };

var elements = original.Descendants("element").Select(element =>
{
    var attributes = element.Attributes().Where(a => required.Contains(a.Name.LocalName));
    return new XElement(element.Name, attributes);
});

var root = new XElement(original.Root.Name, elements);
var newDocument = new XDocument(original.Declaration, root);

Upvotes: 0

alobster
alobster

Reputation: 38

Just add ToArray() method to your foreach loop:

foreach (XAttribute attribute in output.Descendants("element").Attributes().ToArray())
{
    if (!Array.Exists<String>(WS_LookupFields, fieldname => attribute.Name == fieldname)) attribute.Remove();
}

Upvotes: 0

Niklas Wulff
Niklas Wulff

Reputation: 3524

I think you will need two loops:

// Loop all descendants
foreach (var element in output.Descendants("element"))
{
    // for that element, loop all attributes
    foreach (var attribute in element.Attributes())
    {
    if (!Array.Exists<String>(WS_LookupFields, fieldname => attribute.Name == 
fieldname)) attribute.Remove();
    }
}

Upvotes: 0

Related Questions