I'm working on Windows Phone 8 C#/XAML .NET 4.5 Application
I'm trying to select element with a given name from an XML i'm getting, but when i try using Descendants
to select it, it returns empty collection/list/array of results.
It returns fine when no name is selected, but when i try to search with name, it returns empty.
I'm probably just dumb and making a stupid mistake. Do you see some/can you explain?
EXAMPLES:
myXMLString:
<root>
<element>
<thisOne xmlns="something">example</thisOne>
<element>
<others></others>
</root>
code:
XDocument xmlData = XDocument.Parse(myXMLString);
//is always null
var thisOne = xmlData.Root.Descendants("thisOne").FirstOrDefault();
//returns the flattened version of the tree in a list
var descendants = xmlData.Root.Descedants().ToList();
You're currently looking for the elements called thisOne
which aren't in a namespace. You need to specify the something
namespace... the xmlns="something"
part is specifying the default namespace for this element and further descendants. Fortunately, LINQ to XML makes it really easy to use XML namespaces:
XNamespace ns = "something";
var thisOne = xmlData.Root.Descendants(ns + "thisOne").FirstOrDefault();
See more on this question at Stackoverflow