-->

xdocument.root.element and other permutations retu

2019-08-01 16:29发布

问题:

flow.Name definitely equals the 'name' of one of the flows in the flowData XDocument.

XElement rootelem = flowData.Root.Element("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 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>

These two lines return null too:

var xelem2 = flowData.Root.Element(flow.Name);
var xelem3 = flowData.Root.Element("flows").Element(flow.Name);

And these two return empty sets:

var keepgoing = new XDocument(rootelem.Descendants(flow.Name));
var idk = new XDocument(flowData.Descendants(flow.Name));

回答1:

XElement.Element method expects an element name, not an attribute value. It doesn't know which attribute value is the name of your element....

You should try:

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