Domanda

I have the following xml file:

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

<!-- New XML document created with EditiX XML Editor (http://www.editix.com) at Tue Mar 18 22:41:05 IST 2014 
-->
<html xsi:NamespaceSchemaLocation="http://www.w3.org/1999/xhtml DM_Project.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <head>
        <title>title1</title>
    </head>
    <body>
        <fragment name="heading" id="heading1">
            <h1>Heading 1</h1>
        </fragment>
        <fragment name="heading" id="heading2">
            <h2>Heading 2</h2>
        </fragment>
        <fragment name="paragraph" id="paragraph1">
            <p>Paragraph 1</p>
        </fragment>

    </body>
</html>

I have written a LINQ to xml query that extracts everything between the fragment tags, as shown:

XElement xelement = XElement.Load("C:\\Users\\Administrator\\Desktop\\DM_Project.xml");
var contents =
            from content in xelement.Elements("body").Elements("fragment").Descendants()
            select content;
            Console.WriteLine(contents);

The output of which is, as expected:

<h1>Heading 1</h1> 
<h2>Heading 2</h2> 
<p>Paragraph 1</p> 

However, I am trying to write a query that would return everything between the fragment tag with id="heading1", as shown :

XElement xelement = XElement.Load("C:\\Users\\Administrator\\Desktop\\DM_Project.xml");
var contents =
            from content in xelement.Elements("body").Elements("fragment").Descendants()
            where (string)xelement.Attributes("id") == "heading1"
            select content;
            Console.WriteLine(contents);

when I run this query on LINQpad, I get the following error;

Cannot execute text selection: Cannot convert type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>' to 'string'

Can anyone pls point out the mistake I'm doing?

Thank you.

È stato utile?

Soluzione

Try this:

var contents =
    from content in xelement.Elements("body").Elements("fragment")
    where content.Attribute("id").Value == "heading1"
    select content;

You where repeating xelement where content should be on the where clause.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top