选择节点InnerText属性不正确

本文关键字:不正确 属性 InnerText 节点 选择 | 更新日期: 2023-09-27 18:17:53

我试图获得找到的每个父元素的特定节点的值。在本例中,我想返回每个学生的First Name。相反,我将获取每个实例中的第一个元素名称。学生的InnerText是正确的,但是FirstName的InnerText总是Alex。

var xml = @"<School>
                <Students>
                    <Student>
                        <FirstName>Alex</FirstName>
                        <LastName>Smith</LastName>
                        <Grade>11</Grade>
                    </Student>
                    <Student>
                        <FirstName>Joanne</FirstName>
                        <LastName>Robins</LastName>
                        <Grade>12</Grade>
                    </Student>
                    <Student>
                        <FirstName>Steve</FirstName>
                        <LastName>Baker</LastName>
                        <Grade>11</Grade>
                    </Student>
                </Students>
                <Teachers>
                    <Teacher>
                        <FirstName>George</FirstName>
                        <LastName>Roberts</LastName>
                        <Grade>11</Grade>
                    </Teacher>
                    <Teacher>
                        <FirstName>Amanda</FirstName>
                        <LastName>Walker</LastName>
                        <Grade>12</Grade>
                    </Teacher>
                    <Teacher>
                        <FirstName>Tracey</FirstName>
                        <LastName>Smith</LastName>
                        <Grade>12</Grade>
                    </Teacher>
                </Teachers>
            </School>";
var doc = new XmlDocument();
doc.LoadXml(xml);
var resourceTypeNodes = doc.GetElementsByTagName("Student");
var resourceTypesIterator = resourceTypeNodes.GetEnumerator();
while (resourceTypesIterator != null && resourceTypesIterator.MoveNext())
{
    var resourceTypeNode = resourceTypesIterator.Current as XmlNode;
    var typeNameElement = resourceTypeNode.SelectSingleNode("//FirstName");
    Console.WriteLine(resourceTypeNode.InnerXml);
    Console.WriteLine(typeNameElement.InnerText);
}

这是上面代码的输出。

<FirstName>Alex</FirstName><LastName>Smith</LastName><Grade>11</Grade>
Alex
<FirstName>Joanne</FirstName><LastName>Robins</LastName><Grade>12</Grade>
Alex
<FirstName>Steve</FirstName><LastName>Baker</LastName><Grade>11</Grade>
Alex

我错过了什么?

选择节点InnerText属性不正确

因为您使用的是//FirstName XPath表达式,它将始终从根返回第一个节点,所以如果对子节点进行调用并不重要。修改一下:

var typeNameElement = resourceTypeNode.SelectSingleNode("//FirstName");

:

var typeNameElement = resourceTypeNode.SelectSingleNode("FirstName");

此外,您手动使用IEnumerator是否有任何具体原因?你可以用foreach:

来简化你的代码
foreach (XmlNode resourceTypeNode in doc.GetElementsByTagName("Student"))
{
    var typeNameElement = resourceTypeNode.SelectSingleNode("FirstName");
    Console.WriteLine(resourceTypeNode.InnerXml);
    Console.WriteLine(typeNameElement.InnerText);
}