CACuzcatlan
CACuzcatlan

Reputation: 5487

WP7 Linq to XML to get a child element of an XElement by name

I know this is a somewhat easy question, but I haven't been able to make it work even after looking at answers on SO and LINQ to XML tutorials. I'm using Windows Phone 7, but I don't think that should make a difference.

I have XML that looks like this:

<response xmlns="http://anamespace.com/stuff/">
    <error code="ERROR_CODE_1">You have a type 1 error</error>
</response>

I have the XML above loaded into an XElement. I want to get the "error" node. This question says you need to handle the namespace. I've tried my query with and without the namespace and it doesn't work either way.

Query with namespace:

private object ParseElement(XElement responseElement)
{
    XNamespace ns = "http://anamespace.com/stuff/";
    IEnumerable<XElement> errorNodes = from e in responseElement.Elements(ns + "error") select e;
}

Query without namespace:

private object ParseElement(XElement responseElement)
{
    IEnumerable<XElement> errorNodes = from e in responseElement.Elements("error") select e;
}

The errorNodes variable never gets populated with XElements. The tutorials I've read all use this notation for selecting an element by name, but it's not working for me.

Upvotes: 1

Views: 2569

Answers (2)

si618
si618

Reputation: 16848

Any chance you're reading the whole document instead of the error elements?

Does it work if you use Descendants instead of Elements?

[TestMethod]
public void CanGetErrorElements()
{
    string xml = @"
<response xmlns=""http://anamespace.com/stuff"">
<error code=""ERROR_CODE_1"">You have a type 1 error</error>
</response>";
    XDocument doc = XDocument.Parse(xml);
    XNamespace ns = "http://anamespace.com/stuff";
    var errorNodes = from e in doc.Descendants(ns + "error") 
                     select e;
    Assert.IsTrue(errorNodes.Count() > 0);
}

Upvotes: 0

dtb
dtb

Reputation: 217233

This codes Works on my Machine™:

XElement response = XElement.Parse(
@"<response xmlns=""http://anamespace.com/stuff/"">
    <error code=""ERROR_CODE_1"">You have a type 1 error</error>
</response>");

XNamespace ns = "http://anamespace.com/stuff/";

XElement error = response.Element(ns + "error");

string code = (string)error.Attribute("code");
string message = (string)error;

Console.WriteLine(code);
Console.WriteLine(message);

My machine runs regular .NET 4 though, so maybe you can run this code and check if it works for WP7.

Upvotes: 1

Related Questions