Search code examples
vb.netlinq-to-xmlxelement

Get XElement by value of its attribute


I've got the following XML:

<rootNode>
  ... some stuff
  <ReportCellRef>
    <dang n="DVCompany" h="0" u="0" o="0" fmt="0">
      ... some stuff
    </dang>
  </ReportCellRef>
</rootNode>

And I want get the <dang ...> ... </dang> node as XElement, so I can replace it with another node, provided I have the value of the n attribute.

I've got this code:

Dim nameToSearch = importNode.Attribute("n").Value
Dim replaceable = From dangToTake In xdoc.Elements("ReportCellRef") _
                  Where CStr(dangToTake.Element("dang").Attribute("n")) = nameToSearch
                  Select dangToTake

For Each nodeToReplace As XElement In replaceable
    nodeToReplace.ReplaceWith(importNode)
Next nodeToReplace

But the LINQ query does not yield any results... Any ideas?


Solution

  • Throw a "Descendants()" call in there:

    dim xdoc as XDocument = XDocument.Parse("<rootNode><ReportCellRef><dang n=""DVCompany"" h=""0"" u=""0"" o=""0"" fmt=""0""></dang></ReportCellRef></rootNode>")
    Dim replaceable = From dangToTake In xdoc.Descendants().Elements("ReportCellRef") _
                  Where dangToTake.Element("dang").Attribute("n").Value = "DVCompany"
                  Select dangToTake