Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Xml parse with Xdocument

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 ?

like image 372
Evox Avatar asked Jan 18 '26 06:01

Evox


1 Answers

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.

like image 54
Damir Arh Avatar answered Jan 20 '26 20:01

Damir Arh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!