3

I want parse xml in windows store app with Xdocument.

I tried this,but returned with null:

XDocument xDoc;
string title= "";

xDoc = XDocument.Load(url);

var elements = from x in xDoc.Descendants()
               select new
               {
                   title = x.Descendants("title").First().Value,
               };

foreach (var el in elements)
    _title = title;

Xml contents:

<title type='text'>tiitle</title>
<content type='text'> gfgdgdggd</content>
<link rel='related' type='application/atom+xml' href='http....'/>

How can is retrive text from attributes ?

2
  • Please clarify - do you want the value of the title element, or the value of the type attribute. Commented Nov 19, 2012 at 0:22
  • Your XML is invalid. You need to have a single root element. Commented Nov 19, 2012 at 0:26

2 Answers 2

3

As ZevSpitz already mentioned, your XML is invalid. I modified it a bit to be able to test my code:

<root>
    <title type="text">title</title>
    <content type="text">gfgdgdggd</content>
</root>

You can retrieve values from the type attributes with the following code:

XDocument xDoc = XDocument.Parse(xml);

var types =
    from x in xDoc.Root.Descendants()
    select x.Attribute("type").Value;

In my case xml is declared as follows:

private string xml =
    @"<root>
        <title type=""text"">title</title>
        <content type=""text"">gfgdgdggd</content>
    </root>";

You can still use your code to load the XML from a URL if the file contents are the same.

Sign up to request clarification or add additional context in comments.

3 Comments

Good call on using Root. I prefer not to use .Value, and instead cast to a string, because if there is no type attribute on the element the Attribute method will return null and calling the Value property will cause a NullReferenceException. If casting to string, the returned value will simply be null, which the string type can hold.
@ZevSpitz I guess it depends on the expected XML structure, but I like your approach. I'm sure it'll come in handy. I usually used != null checking in such cases.
0

Try:

var types =
    from e in xDoc.Descendants()
    select (string)e.Attribute("type");

foreach (string type in types) {
    Console.WriteLine(type);
}

1 Comment

Does it return null for all the elements? or only for one of them?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.