0

I have the following xml file which consists of html tags, as shown below:

<?xml version="1.0" encoding="UTF-8"?>

<html>
<head>
<title>
title1
</title>
</head>

<body>
<fragment id="heading1">
<h1>
Heading 1
</h1>
</fragment>
<fragment id="heading2">
<h2>
Heading 2
</h2>
</fragment>
<fragment id="paragraph1">
<p>
Paragraph 1
</p>
</fragment>
</body>                  
</html>

I am trying to extract all the fragment ids and display them using linq-xml. The query is shown below:

XDocument xelement = XDocument.Load("Path\\To\\XMLFile"); 
var name = from nm in xelement.Descendants("body")
select nm.Element("fragment").Attribute("id").Value;
Console.WriteLine(name);

The output this query returns is:

heading1

But what I want is:

heading1 heading2 paragraph1

What am I doing wrong? Kindly advice.

Thank you

2 Answers 2

2

You can select the values using

IEnumerable<string> names = from id in xelement.Descendants("fragment").Attributes("id") select id.Value;

or

IEnumerable<string> names = from frag in xelement.Descendants("fragment") select frag.Attribute("id").Value;
0
1

I have tested and its working fine!!

XDocument po = XDocument.Load(@"XMLFile1.xml");
      IEnumerable<string> names = from id in po.Descendants("fragment").Attributes("id") select id.Value;
            string str = string.Empty;
            foreach (var el in names)
            {
                str += el;               
            }
            System.Console.WriteLine(str);
            Console.ReadKey();
2
  • Thank you Neel. But could u explain wy it did not work with XDocument?
    – Anvith
    Mar 24, 2014 at 13:33
  • it works with XDocument see my updated answer @Anvith
    – Neel
    Mar 24, 2014 at 13:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.