Syspect
Syspect

Reputation: 921

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?

Upvotes: 1

Views: 2480

Answers (2)

Crowcoder
Crowcoder

Reputation: 11514

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

Upvotes: 0

Chris Dunaway
Chris Dunaway

Reputation: 11216

You're comparing an XAttribute against its value. CStr(dangToTake.Element("dang").Attribute("n")) does not give you the value of the attribute. Try dangToTake.Element("dang").Attribute("n").Value instead.

Upvotes: 1

Related Questions