Pregunta

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

¿Fue útil?

Solución 2

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();

Otros consejos

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;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top