xdocument.root.element and other permutations return null

橙三吉。 提交于 2019-12-11 13:28:56

问题


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


来源:https://stackoverflow.com/questions/24650364/xdocument-root-element-and-other-permutations-return-null

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