XML Reading

A

André Freitas

I got a xml file like this:

<menu>
<categoria imagem="a">
<item nome="b" />
<item nome="c" />
<item nome="d" />
</categoria>
<categoria imagem="e">
<item nome="f" />
<item nome="g" />
</categoria>
</menu>

How can I read each of this values, like:

a
b
c
d

f
g
h

I dont know how many <category> i ll get, and how many <item> inside each
<category>.

Regards,
André
 
M

Martin Honnen

André Freitas said:
I got a xml file like this:

<menu>
<categoria imagem="a">
<item nome="b" />
<item nome="c" />
<item nome="d" />
</categoria>
<categoria imagem="e">
<item nome="f" />
<item nome="g" />
</categoria>
</menu>

How can I read each of this values, like:

a
b
c
d

f
g
h

With .NET 3.5 you can use LINQ to XML
(http://msdn.microsoft.com/en-us/library/bb387098.aspx), here is an example:

XDocument doc = XDocument.Load("file.xml");
var query = from cat in doc.Root.Elements("categoria")
select new
{
imagem = (string)cat.Attribute("imagem"),
names = from item in cat.Elements("item")
select (string)item.Attribute("nome")
};

Here is how you could output the data:

foreach (var cat in query)
{
Console.WriteLine("{0}:", cat.imagem);
foreach (string name in cat.names)
{
Console.WriteLine("\t{0}", name);
}
Console.WriteLine();
}
 
A

André Freitas

thx so much

Martin Honnen said:
With .NET 3.5 you can use LINQ to XML
(http://msdn.microsoft.com/en-us/library/bb387098.aspx), here is an
example:

XDocument doc = XDocument.Load("file.xml");
var query = from cat in doc.Root.Elements("categoria")
select new
{
imagem = (string)cat.Attribute("imagem"),
names = from item in cat.Elements("item")
select (string)item.Attribute("nome")
};

Here is how you could output the data:

foreach (var cat in query)
{
Console.WriteLine("{0}:", cat.imagem);
foreach (string name in cat.names)
{
Console.WriteLine("\t{0}", name);
}
Console.WriteLine();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top