2017-04-13 54 views
0

這裏是我的工作的xml文件的例子:如何分析使用XmlDocument的C#與孩子XML屬性?

<PhysicalChains> 
    <Chain IDValue="Chilis"> 
     <ChainID> 
      <BrandName>Chilis Restaurant</BrandName> 
      <Information> 
       <PhoneNumber>111-222-3333</PhoneNumber> 
      </Information> 
     </ChainID> 
    </Chain> 
    <Chain IDValue="Longhorn"> 
     <ChainID> 
      <BrandName>Longhorn Bar and Grill</BrandName> 
      <Information> 
       <PhoneNumber>555-222-4444</PhoneNumber> 
      </Information> 
     </ChainID> 
    </Chain> 
    ... 
    ... 
</PhysicalChains> 

我只是想拉孩子的屬性輸出格式爲:

Restaurant ID: Chilis 
Restaurant Name: Chilis Restaurant 
Restaurant Phone Number: 111-222-3333 

Restaurant ID: Longhorn 
Restaurant Name: Longhorn Bar and Grill 
Restaurant Phone Number: 555-222-4444 

.... 
.... 

這是我有這樣的代碼遠:

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.LoadXml("https://example.com/feeds/myFeed.xml"); 

XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("/PhysicalChains/Chain"); 

foreach (XmlNode node in nodes) 
{ 
    // This first line works just fine. 
    Console.WriteLine("Resturant ID: " + node.Attributes["IDValue"].Value + "\n"); 

    // I need to know how to pull the other information above here 

} 

我試圖讓BrandName財產像這樣,但它沒有工作:

Console.WriteLine("Restaurant Name: " + node.SelectSingleNode("BrandName").InnerText + "\n"); 

誰能幫助?

+1

如果這是一個選項Linq有足夠的支持,讓你在一個語句中做到這一點。在這裏搜索Liqn Xml與a有很多相關的q。 –

回答

0

你不能只用SelectSingleNode直接到達子節點的孩子。首先,導航到ChainID節點,然後嘗試導航到BrandName節點。像這樣:

var child1 = node.SelectSingleNode("ChainID"); 
var child2 = child1.SelectSingleNode("BrandName"); 

Console.WriteLine("Restaurant Name: " + child2.InnerText + "\n\n");