简体   繁体   中英

XElement.Root.Element keeps returning null

I am learning C# and trying to flatten XML following this code from this post

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

This is my XML (sorry I don't know how to post fancy code style)

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

There is namespace so I changed var member = doc.Root.Element(ns + "member"); to var member = doc.Root.Element("ApplicationExtraction"); but this returns NULL.

I also try XElement sRoot = doc.Root.Element("ApplicationExtraction"); from this post I still get the same result.

I read up Microsoft XElement document but don't see how I can fix this.

What could I have done wrong?

In your XML, doc.Root is the root node ie ApplicationExtraction and there is no node ApplicationExtraction inside the root node thus you are getting null.

To fetch any specific node you need(for example):-

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

and to fetch the value inside the node:-

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

will look for an element 'ApplicationExtraction' inside the Root. If you want the Root, just reference

doc.Root

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM