Cowmoogun
Cowmoogun

Reputation: 2567

Remove two elements in XML using linq

I want to remove two elements from an XML using LINQ if one value is null. What I tried was this:

xml.Descendants("MarketingSpecial")
   .Where(Function(m)  Document.Descendants("MarketingPrice").Value() = "0.00")
   .Remove()
xml.Descendants("MarketingPrice")
   .Where(Function(m) m.Value() = "0.00")
   .Remove()

But it removes MarketingPrice correctly, but removes MarketingSpecial everywhere. How can I only remove MarketingSpecial when i remove MarketingPrice?

The xml is formatted as follows:

<Inventory pt="0.159">
    <Vehicle>
       <MarketingSpecial><![CDATA[ Yes ]]></MarketingSpecial>
       <MarketingPrice>0.00</MarketingPrice>
    </Vehicle>
</Inventory>

Upvotes: 1

Views: 48

Answers (2)

ocuenca
ocuenca

Reputation: 39376

You can select the elements you need to delete in the same query:

xml.Descendants("Vehicle").Where(Function(m) m.Element("MarketingPrice").Value() = "0.00")
                          .SelectMany(Function(e) e.Elements()
                                                   .Where(Function(x) x.Name="MarketingSpecial"
                                                                   Or x.Name="MarketingPrice"))
                          .Remove()

Upvotes: 0

krillgar
krillgar

Reputation: 12815

You should look for the sibling MarketingPrice as opposed to any within the entire Tree when looking for the MarketingSpecial's MarketingPrice.

xml.Descendants("MarketingSpecial")
   .Where(Function(m)  m.ParentNode().Descendants("MarketingPrice").Value() = "0.00")
   .Remove()

Within your function inside the Where clause, your m is the current MarketingSpecial node. Go up to its parent, and check its descendants for the MarketingPrice. That will give you what you're looking for.

Upvotes: 1

Related Questions