Get XElement by value of its attribute

*爱你&永不变心* 提交于 2020-01-16 05:09:12

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/28675704/get-xelement-by-value-of-its-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!