问题
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