循环遍历XML文件并仅显示所选节点

时间:2014-02-22 17:26:47

标签: c# xml windows-phone-8

我正在检索一个在线XML文件,我想遍历该文件并仅使用Node'name'的内容。知道我该怎么做吗?

这是我的XML文件:

<?xml version='1.0' encoding='UTF-8'?>
<data><set name='Cuba Libre 43' id='10'>
<name>Cuba Libre 43</name>
<howto>Fill a highball glass half full with ice cubes. Add 3 cl rum, 3 cl of licor and 12 cl of cola, a few drops of squeezed lime and stir. Put a slice of lemon on the rim to finish.</howto>
<ingredient category='0'>Licor 43</ingredient>
<ingredient category='2'>Dark Rum</ingredient>
<ingredient category='0'>Cola</ingredient>
<ingredient category='0'>Ice cubes</ingredient>
<ingredient category='0'>Lemon wedge</ingredient>
<ingredient category='0'>Drops of squeezed lime</ingredient>
</set><set name='Blanco 43' id='11'>
<name>Blanco 43</name>
<howto>Put some ice cubes in the glass. Then add one part liqor and then 3 parts of milk.</howto>
<ingredient category='0'>Licor 43</ingredient>
<ingredient category='0'>Cold milk</ingredient>
<ingredient category='0'>Ice cubes</ingredient>
</set><set name='Dreamsicle' id='12'>
<name>Dreamsicle</name>
<howto>Put some ice cubes in a glass. Then add 1 part liqor, 2 parts milk and 2 part orange juice.</howto>
<ingredient category='0'>Licor 43</ingredient>
<ingredient category='0'>Milk</ingredient>
<ingredient category='0'>Orange juice</ingredient>
<ingredient category='0'>Ice cubes</ingredient>
</set><set name='Don Juan' id='13'>
<name>Don Juan</name>
<howto>Put some ice cubes in the glass. Then add 1 part licor and 3 parts orange juice.</howto>
<ingredient category='0'>Licor 43</ingredient>
<ingredient category='0'>Orange juice</ingredient>
<ingredient category='0'>Ice cubes</ingredient>
</set></data>

2 个答案:

答案 0 :(得分:3)

轻松Linq To Xml

XDocument xDoc = XDocument.Parse(xmlString);

var names = xDoc.Descendants("name").Select(n => n.Value).ToList();

答案 1 :(得分:0)

没有LINQ / XMLDocument:

XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
while (rdr.Read())
{
    if (rdr.NodeType == XmlNodeType.Element)
    {
       if (rdr.LocalName.Equals("name"))
       {
           Console.WriteLine(rdr.Value);
       }
    }
 }