简体   繁体   English

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

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

Here's an example of the xml file I'm working with: 这是我正在使用的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>

I'm simply trying to pull the children properties to output this format: 我只是想拉孩子属性以输出这种格式:

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

....
....

Here's the code I have so far: 这是我到目前为止的代码:

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

}

I've tried getting BrandName property like so, but it didn't work: 我已经尝试过像这样获取BrandName属性,但没有成功:

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

Can anyone help? 有人可以帮忙吗?

You can't just use SelectSingleNode to directly reach a child of a child node. 您不能只使用SelectSingleNode直接到达子节点的子节点。 First, navigate to the ChainID node, then try to navigate to the BrandName node. 首先,导航到ChainID节点,然后尝试导航到BrandName节点。 Like so: 像这样:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM