xdocument.root.element和其他排列返回null [英] xdocument.root.element and other permutations return null
问题描述
flow.Name绝对等于flowData XDocument中流之一的名称".
flow.Name definitely equals the 'name' of one of the flows in the flowData XDocument.
XElement rootelem = flowData.Root.Element("flows");
在上面的行之后,rootelem包含flows元素,并且它是预期的子元素,但下面的行引发了空引用异常,为什么?
after the above line the rootelem contains the flows element and it's children as expected BUT the below line throws a null reference exception, why?
flowData.Root.Element(flow.Name).Remove();
flowData 被声明为 XDocument ,如下所示:
flowData is declared as an XDocument and looks like so:
<?xml version="1.0" encoding="UTF-8"?>
-<D53ESB>
-<comms>
<diagnosticemails sender="eventlog"/>
</comms>
-<globalparams>
<!-- some comments... -->
</globalparams>
-<flows>
-<flow webserviceonly="false" stoponerror="true" name="testFlow">
-<action name="t1">
<schedule firsttime="01/01/2014 14:10:00" every="600000"/>
-<adapter name="GetXml">
<param name="url" value="http://xml.betfred.com/Football-Championship.xml"/>
</adapter>
</action>
</flow>
...more flows
</flows>
</D53ESB>
这两行也返回null:
These two lines return null too:
var xelem2 = flowData.Root.Element(flow.Name);
var xelem3 = flowData.Root.Element("flows").Element(flow.Name);
这两个返回空集:
var keepgoing = new XDocument(rootelem.Descendants(flow.Name));
var idk = new XDocument(flowData.Descendants(flow.Name));
推荐答案
XElement.Element
方法需要元素名称,而不是属性值.它不知道哪个属性值是元素的名称....
XElement.Element
method expects an element name, not an attribute value. It doesn't know which attribute value is the name of your element....
您应该尝试:
flowData.Root.Element("flows")
.Elements("flow")
.Where(f => (string)f.Attribute("name") == flow.Name);
这篇关于xdocument.root.element和其他排列返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!