Yoav
Yoav

Reputation: 2077

How to write simple query to XElement?

Trying to use Linq to XML for the first time and having some problems. I have this XML file that needs to be read and used for various tasks. The file contains a list of entities called 'interfaces'. To start with I want to display a list of names of these interfaces.

Here is the XML file:

<?xml version="1.0" encoding="utf-8" ?>
<InterfaceList>
  <Interface>
    <InterfaceName>Account Lookup</InterfaceName>
    <RequestXSD>ALREQ.xsd</RequestXSD>
    <ResponseXSD>ALRES.xsd</ResponseXSD>
  </Interface>
  <Interface>
    <InterfaceName>Balance Inquiry</InterfaceName>
    <RequestXSD>BIREQ.xsd</RequestXSD>
    <ResponseXSD>BIRES.xsd</ResponseXSD>
  </Interface>
</InterfaceList>

Here is the query code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Stub {
    public class InterfaceList : XElement {

        public void GetInterfaceNameList() {
            var v = from interface in this.Elements("Interface")
                select interface.Element("InterfaceName").Value;
        }
    }
}

The idea is to load InterfaceList from the file, and then to use it to query any I may need. The problem is that I'm getting error message for everything in the query. here are a few of them:

What's wrong here?

Upvotes: 0

Views: 978

Answers (1)

Simon
Simon

Reputation: 5493

If you want to call your variable 'interface' (which is a reserved word) you will need to escape it, like this:

var v = from @interface in this.Elements("Interface")
        select @interface.Element("InterfaceName").Value;

Probably better to just rename it though....

Upvotes: 1

Related Questions