Get XML value

2

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

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

I tried this way but I could not:

var ns = xDoc.Root.GetDefaultNamespace();

            string strin = xDoc.Descendants(ns + "boolean").ToString();
    
asked by anonymous 29.03.2014 / 16:39

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 this does:

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

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

% w / w ( MSDN in English ) returns a Descendants and not a simple element. This is because there may be multiple nodes in an XML document with the same name. To convert IEnumerable<XElement> to IEnumerable , we use the methods XElement , First or Single :

  • FirstOrDefault ( MSDN in English ): Returns the first element found with the given name. Exception if there are none.
  • First ( MSDN in English ): Returns the first element found with the given name. Returns FirstOrDefault if there are none.
  • null ( MSDN in English ): Returns the unique element found with the given name. Exception if there are none or if there is more than one element.

Finally, having the node, we use the Value ( MSDN in English ) to get the textual content of the node.

    
29.03.2014 / 16:49