xdocument.root.element和其他排列返回null

时间:2014-07-09 09:46:47

标签: c# xml linq-to-xml xelement

flow.Name肯定等于flowData XDocument中其中一个流的“名称”。

XElement rootelem = flowData.Root.Element("flows");

在上面的行之后,rootelem包含了流元素,并且它的子节点是预期的但是下面的行抛出了一个空引用异常,为什么?

flowData.Root.Element(flow.Name).Remove();

flowData 被声明为 XDocument ,如下所示:

<?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:

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));

1 个答案:

答案 0 :(得分:2)

XElement.Element方法需要元素名称,而不是属性值。它不知道哪个属性值是元素的名称....

你应该尝试:

flowData.Root.Element("flows")
.Elements("flow")
.Where(f => (string)f.Attribute("name") == flow.Name);
相关问题