GowthamanSS
GowthamanSS

Reputation: 1474

Get xml node value c#

Let us consider the following xml as

<?xml version="1.0" encoding="UTF-8" ?>
   <response success="true">
       <struct>value</struct>
   </response>

while parsing i am getting following error as

Root element is missing.

the code which i used was

foreach (XElement carselement in xdoc.Descendants("response"))
                {
                  String  value= carselement.Element("struct").Value;

                }

waiting for your solutions

Upvotes: 1

Views: 246

Answers (2)

user2246674
user2246674

Reputation: 7719

The XML input is not as expected (it is "empty") and the exception occurs during XDocument.Load (or XDocument.Parse, etc).

Ultimately xdoc does not contain what is expected - and the "suspect" lines never even run; again, this Exception is caused when the XML is parsed, not when it is enumerated/navigated. This scenario should be easily identified with an attached debugger or stack-trace.

Here is some minimal code that can be run in LINQPad as C# statements. I've modified it just enough to display nicely with dump. Note that it runs as expected.

var xmlStr = @"<?xml version=""1.0"" encoding=""UTF-8"" ?>
   <response success=""true"">
       <struct>value</struct>
   </response>";
var xdoc = XDocument.Parse(xmlStr);
xdoc.Descendants("response")
    .Select(e => e.Element("struct").Value)
    .Dump();

Here is how the exception can be caused (and it has nothing to do with Descendants or other enumeration/navigation):

var xmlStr = @"<?xml version=""1.0"" encoding=""UTF-8"" ?>";
var xdoc = XDocument.Parse(xmlStr);
// --> XmlException: Root element is missing

Upvotes: 1

Csaba Toth
Csaba Toth

Reputation: 10699

Maybe your XML is over simplified, and looks like this:

<!-- example -->
<?xml version="1.0" encoding="UTF-8" ?>
<response success="true">
    <struct>value1</struct>
</response>
<response success="true">
    <struct>value2</struct>
</response>
<response success="false">
    <struct>value3</struct>
</response>

In this case you are missing a <responses></responses> which wraps around the response array of elements.

BTW, your code should work also, if your XML file is really what you quote here. Do you try to manipulate the XML too?

XDocument xdoc = XDocument.Load(filePath);
if (xdoc == null) return;

XElement response = xdoc.Descendants("response").FirstOrDefault();
XElement structElement = response.Descendants("struct").FirstOrDefault();

Upvotes: 0

Related Questions