【问题标题】:xdocument.root.element and other permutations return nullxdocument.root.element 和其他排列返回 null
【发布时间】:2014-07-09 09:46:47
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    你应该试试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      • 2015-06-11
      相关资源
      最近更新 更多