2014-02-22 92 views
0

我正在檢索在線XML文件,並且我想遍歷文件並僅使用Node'name'的內容。任何想法我應該如何去做?通過XML文件循環並僅顯示所選節點

這是我的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> 

回答

3

易與Linq To Xml

XDocument xDoc = XDocument.Parse(xmlString); 

var names = xDoc.Descendants("name").Select(n => n.Value).ToList(); 
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); 
     } 
    } 
}