Skip to main content
 首页 » 编程设计

c#之XElement.Root.Element 不断返回 null

2024年02月05日10java哥

我正在学习 C# 并尝试按照来自 this post 的这段代码来扁平化 XML

var doc = XDocument.Load("test.xml"); 
XNamespace ns = "mynamespace"; 
var member = doc.Root.Element(ns + "member"); 
 
// This will *sort* of flatten, but create copies... 
var descendants = member.Descendants().ToList(); 
 
// So we need to strip child elements from everywhere... 
// (but only elements, not text nodes). The ToList() call 
// materializes the query, so we're not removing while we're iterating. 
foreach (var nested in descendants.Elements().ToList()) 
{ 
    nested.Remove(); 
} 
member.ReplaceNodes(descendants); 

这是我的 XML(抱歉,我不知道如何发布花哨的代码样式)

<ApplicationExtraction> 
    <IsCurrent>Yes</IsCurrent> 
    <ApplicationDate>10/06/2015</ApplicationDate> 
    <Status>Application Received</Status> 
    <EquipmentType>Equipment</EquipmentType> 
    <IsLoan>No</IsLoan> 
</ApplicationExtraction> 

有命名空间,所以我将 var member = doc.Root.Element(ns + "member"); 更改为 var member = doc.Root.Element("ApplicationExtraction"); 但这返回 NULL。

我也尝试 XElement sRoot = doc.Root.Element("ApplicationExtraction"); 来自 this post我仍然得到相同的结果。

我阅读了 Microsoft XElement 文档,但不知道如何解决这个问题。

我可能做错了什么?

请您参考如下方法:

XElement sRoot = doc.Root.Element("ApplicationExtraction"); 

将在 Root 中查找元素“ApplicationExtraction”。 如果你想要根,只需引用

doc.Root