bircastri
bircastri

Reputation: 153

Querying XML file

i should to parse an XML file in my C# application.

This is a sample of my XML file

<?xml version="1.0" encoding="utf-8" ?>
  <tokens>
    <token id="1" >
      <id>1</id>
      <nome>"Pippo"</nome>
      <numeroSillabe>"2"</numeroSillabe>
      <sillabaIniziale>"Pip"</sillabaIniziale>
    </token>

    <token id="2">
        <id>2</id>
        <nome>Pluto</nome>
        <numeroSillabe>2</numeroSillabe>
        <sillabaIniziale>Plu</sillabaIniziale>
      </token>

    <token id="3">
        <id>3</id>
        <nome>Palla</nome>
        <numeroSillabe>2</numeroSillabe>
        <sillabaIniziale>Pa</sillabaIniziale>
      </token>
</tokens>

For reading this file i use this code

XmlDocument document = new XMLDocument()
document.Load("Content\\Token.xml");

// arrivo al nodo
//XmlNode node = document.DocumentElement.SelectSingleNode("/tokens/token");
//dichiaro la mappa per i token
Dictionary<string, Token> mappa = new Dictionary<string, Token>();
foreach (XmlNode node in document.DocumentElement.ChildNodes)
{
    //creo l'oggetto Token e lo popolo con i risultati del parse
    Token token = new Token();
    //compilo il campo ID
    token.setId((node["id"].InnerText).Replace("\"", ""));
    //compilo il nome
    token.setNome((node["nome"].InnerText).Replace("\"", ""));
    //compilo l numero sillabe
    token.setNumeroSillabe((node["numeroSillabe"].InnerText).Replace("\"", "")); 
    //compilo la sillaba iniziale
    token.setSillabaIniziale(node["sillabaIniziale"].InnerText);
    //aggiungo all array il token
    mappa.Add(token.getId(), token);
}

It works.

Now i would like to search the element from XML document for example SELECT * FROM DOCUMENT_XML WHERE numeroSilabe=2.

How can I perform this task?

Upvotes: 1

Views: 156

Answers (4)

SpiderCode
SpiderCode

Reputation: 10122

Try below code to get filtered nodes without any loop:

var document = new XmlDocument();
document.Load("Content\\Token.xml");
var filteredNodes = document.SelectNodes("tokens/token/numeroSillabe=2");

Upvotes: 0

SoftSan
SoftSan

Reputation: 2472

use this:

var mappa =  document.SelectNodes("//token[numeroSillabe=2]");

Upvotes: 0

Rubens Farias
Rubens Farias

Reputation: 57936

If you need to navigate through your XML file, like in your code sample, you could go with something like this:

var mappa = document.SelectNodes("/tokens/token[numeroSillabe=2]") // Filter
    .OfType<XmlElement>()
    .ToDictionary(
        t => t.GetAttribute("id"),
        t => new
        {
            Id              = t.GetAttribute("id"),
            Nome            = t.SelectSingleNode("nome"           ).InnerText,
            NumeroSillabe   = t.SelectSingleNode("numeroSillabe"  ).InnerText,
            SillabaIniziale = t.SelectSingleNode("sillabaIniziale").InnerText
        });

Upvotes: 1

Christos
Christos

Reputation: 53958

List<Token> tokens = mappa.Select(x=>x.Values.Where(y=>y.getNumeroSillabe()==2)).ToList();

I suppose that your token class has a method getNumeroSillabe() like getId(), which returns the value of NumeroSillabe.

By the way, I would suggest you to use automatic properties instead of defining foreach variable of your class a getter and a setter. Certainly, that would be suitable, if you don't have any logic in this methods instead of setting and getting the value of a variable, without checking anything or doing any calculation etc.

In your case:

// I don't know, which is the access modifier your class and I suppose that is public.

public class Token
{
    public string Id              { get; set;}
    public string Nome            { get; set;}
    public string NumeroSillabe   { get; set;}
    public string SillabeIniziale { get; set;}

    // here goes the methods of your class, if there are any 
}

making this change, the code for the above linq query changes to the following:

List<Token> tokens = mappa.Select(x=>x.Values.Where(y=>y.NumeroSillabe==2)).ToList();

Also your code changes for instance as follows:

token.Nome = node["nome"].InnerText.Replace("\"", "");

The same holds for the other three assignments.

For further reading regrading the auto implemented properties, please look in the following link:

http://msdn.microsoft.com/en-us/library/vstudio/bb384054.aspx

Upvotes: 0

Related Questions