XElement.Root.Element继续返回null

时间:2015-12-15 15:52:36

标签: c# xml linq

我正在学习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。

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

我阅读了Microsoft XElement文档,但没看到我如何解决这个问题。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

在您的XML中,doc.Root是根节点,即ApplicationExtraction,根节点内没有节点ApplicationExtraction,因此您将获得空。

要获取所需的任何特定节点(例如): -

XElement member = doc.Root.Element("IsCurrent");

并获取节点内的值: -

string member = (string)doc.Root.Element("IsCurrent");

答案 1 :(得分:2)

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

将在Root中查找元素'ApplicationExtraction'。 如果你想要Root,只需参考

doc.Root