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

时间:2017-04-13 18:23:31

标签: c# xml xmldocument

以下是我正在使用的$sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS FROM normalW WHERE id = '$id'"; 文件的示例:

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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

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

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

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