I have an xml document that goes like this:
<Menu>
<Category name="Comida Rapida">
<Food cocina="si">
<Name>Haburguesa</Name>
<Price>10</Price>
</Food>
<Food>
<Name>Papas Fritas</Name>
<Price>20</Price>
</Food>
</Category>
<Category name="Bebidas">
<Food>
<Name>Pepsi</Name>
<Price>30</Price>
</Food>
<Food cocina="si">
<Name>Coca Cola</Name>
<Price>40</Price>
</Food>
</Category>
</Menu>
What I want to do is go through each <Category>
checking if the attribute is what I need, for example "Bebidas", so the part I'm interested in is:
<Food>
<Name>Pepsi</Name>
<Price>30</Price>
</Food>
<Food cocina="si">
<Name>Coca Cola</Name>
<Price>40</Price>
</Food>
Now that I have this I want to do something similar to what I have done already:
First I want to print out all:
Pepsi 30
Coca Cola 40
And the I want to print out only the ones that food had the attribute cocina="si"
, so:
Coca Cola 40
So I have various questions:
First of all which approach to use, I am confused by the abundance of possible methods and implementations: XmlDocument, XmlReader, XmlTextReader, etc.
From this question I gather XmlDocument is the easier to use, that would be great, the simpler, the better as I am quite new to parsing Xml files as you can appreciate.
Now to the actual implementation, I have tried all sort of things with not much succes, I seem to be able to do some parts but not all together.
XmlNodeList elemList = doc.GetElementsByTagName("Category");
for (int i = 0; i < elemList.Count; i++)
{
Console.WriteLine(elemList[i].InnerXml);
}
This will output:
<Food><Name>Haburguesa</Name><Price>10</Price></Food><Food><Name>Papas Fritas</Name><Price>20</Price></Food>
<Food><Name>Pepsi</Name><Price>30</Price></Food><Food><Name>Coca Cola</Name><Price>40</Price></Food>
Which makes sense but now, how do I check if the category has the attribute name="cocina"
?
I'm guessing something like this could help:
for (int j = 0; j < elemList[i].Attributes.Count; j++)
{
//??
}
But I can't find something like MoveToAttribute()
in XmlTextReader.
And then again, how do I check whether has the attribute cocina="si"
?
I think LINQ to XML would be the easiest method here:
You have to use
XDocument
class here. Create your document object using static methodsXDocument.Parse(DOCUMENT)
- to load document from string - orXDocument.Load(PATH)
- to load a document from file with given path.After that you can easily find what you are looking for by a query like that:
To make it more clear I'll try to describe what that query does: