如何使用XPath获取XML节点的属性值

时间:2012-05-04 22:59:22

标签: c# xml xpath

这是我的脚本,但它只在控制台中打印空格。有人可以解释我如何使用xPath从XML文件中获取属性值吗?

    XPathNavigator nav;
    XPathDocument docNav;
    XPathNodeIterator NodeIter;
    XmlNamespaceManager ns;

    Int32 elementCount;

    String windowName;

    private void Form1_Load(object sender, EventArgs e)
    {
        docNav = new XPathDocument("C:/BlueEyeMacro/DaMaGeX/Applications/WindowBuilder/GUI.xml");
        nav = docNav.CreateNavigator();
        ns = new XmlNamespaceManager(nav.NameTable); 
        elementCount = nav.Select("/GUI/window").Count;
        Console.WriteLine(elementCount);
        for (int i = 1; i <= elementCount; i++)
        {
            NodeIter = nav.Select("/GUI/window[@ID="+i+"]");
            windowName = NodeIter.Current.GetAttribute("name", ns.DefaultNamespace);
            Console.WriteLine("{0}", windowName);
        }
    }
}

XML文件
<GUI>
<window ID="1" name="mainWindow" parent="0" type="0" text="My first window" options="Option 1;" actions="action 1;" exit="exit;" />
<window ID="2" name="secondWindow" parent="0" type="0" text="My second window" options="Option 1;" actions="action 1;" exit="exit;" />
<window ID="3" name="thirdWindow" parent="0" type="0" text="My third window" options="Option 1;" actions="action 1;" exit="exit;" />
</GUI>

3 个答案:

答案 0 :(得分:3)

我想,你必须先调用NodeIter.MoveNext(),如下代码所示:

XPathNodeIterator nodesText = nodesNavigator.SelectDescendants(XPathNodeType.Text, false);

while (nodesText.MoveNext())
{
    Console.Write(nodesText.Current.Name);
    Console.WriteLine(nodesText.Current.Value);
}

答案 1 :(得分:1)

您可以直接获取属性的字符串值:

    for (int i = 1; i <= elementCount; i++) 
    { 
     // This obtains the value of the @name attribute directly
     string val = 
               nav.Evaluate("string(/GUI/window[@ID='"+i+"']/@name)") as string;                
     Console.WriteLine(val); 
    }

答案 2 :(得分:0)

您还可以修改代码来执行此操作:

    for (int i = 1; i <= elementCount; i++) 
    { 
        var NodeIter = nav.SelectSingleNode("/GUI/window[@ID='"+i+"']/@name"); //This selects the @name attribute directly
        Console.WriteLine("{0}", NodeIter.Value); 
    }

鉴于您正在通过唯一ID识别节点,SelectSingleNode更适合您要执行的操作。