Get value from XML

Asked

Viewed 338 times

2

I’m having trouble getting the value true of this XML:

<boolean xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</boolean>

I tried this way but I couldn’t:

var ns = xDoc.Root.GetDefaultNamespace();

            string strin = xDoc.Descendants(ns + "boolean").ToString();

1 answer

4


Try this:

var nodeName = XNamespace.Get("http://schemas.microsoft.com/2003/10/Serialization/") + "boolean";
string value = xDoc.Descendants(nodeName).First().Value;

What does this do:

First we create a node name, with the namespace and the given name. O GetDefaultNamespace only works if the root node has a xmlns of http://schemas.microsoft.com/2003/10/Serialization/. When the boolean is the root, then the GetDefaultNamespace works:

var nodeName = xDoc.Root.GetDefaultNamespace() + "boolean";
string value = xDoc.Descendants(nodeName).First().Value;

The Descendants (MSDN) return a IEnumerable<XElement> and not a simple element. This is because there can be multiple nodes in an XML document with the same name. To convert the IEnumerable in a XElement, we use the methods First, Single or FirstOrDefault:

  • First (MSDN): Returns the first element found with the given name. Exception if there is no.
  • FirstOrDefault (MSDNs): Returns the first element found with the given name. Returns null if there is no.
  • Single (MSDN): Returns the only element found with the given name. Exception if there is none or if there is more than one widget.

Finally, having the knot, we use Value (MSDN) to obtain the textual content of the node.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.