如何使用 C# 使用 XmlDocument 解析子 XML 属性?

How to parse a child XML property with C# using XmlDocument?

这是我正在使用的 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");

有人能帮忙吗?

您不能只使用 SelectSingleNode 直接到达子节点的子节点。首先,导航到 ChainID 节点,然后尝试导航到 BrandName 节点。像这样:

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

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