无法使用C#XPath获取属性值

时间:2014-07-11 13:28:06

标签: c# xml xpath

我已经花了这么多时间用这个,仍然无法获得NTE属性的值。有人可以帮忙吗?

C#

        StreamReader sr = new StreamReader(resp.GetResponseStream());
        XPathDocument xmlDoc = new XPathDocument(sr); // holds xml document
        XPathNavigator xmlNav = xmlDoc.CreateNavigator(); //evaluates XPath expressions
        XPathNodeIterator node = xmlNav.Select("/DATA2SC/CALL");
        string dne = xmlNav.GetAttribute("NTE", "");

        Console.WriteLine(dne);
        sr.Close();

XML

<?xml version="1.0"?>
<DATA2SC PIN="00000">
    <CALL
    TR_NUM="00000001"
    STATUS="WAITING_FOR_APPROVAL"
    NTE="$15.00">
        <PROBLEM>
            Text
        </PROBLEM>
    </CALL>
</DATA2SC>

2 个答案:

答案 0 :(得分:0)

Select方法返回具有指定XPath的所有节点的集合。

您可以使用SelectSingleNode来选择第一个节点。

    var node = xmlNav.SelectSingleNode("/DATA2SC/CALL");
    string dne = node.GetAttribute("NTE", "");

答案 1 :(得分:0)

请问这个代码吗?

我已经检查过它的工作

    StreamReader sr = new StreamReader("c:\\x.xml");
    XPathDocument xmlDoc = new XPathDocument(sr); // holds xml document
    XPathNavigator xmlNav = xmlDoc.CreateNavigator(); //evaluates XPath expressions


    var node = xmlNav.SelectSingleNode("/DATA2SC/CALL");
    string dne = node.GetAttribute("NTE", "");

    Console.WriteLine(dne);

OR

    XDocument docXmlWorld = XDocument.Load("c:\\x.xml");
    foreach (var node1 in docXmlWorld.Descendants("DATA2SC"))
    {
        foreach (var node2 in node1.Descendants("CALL"))
        {
            string dne = node2.Attribute("NTE").Value;
            Console.Out.WriteLine(dne);
        }
    }

或者你也可以这样做:

    XDocument docXmlWorld = XDocument.Load("c:\\x.xml");
    //Get the first child => [DATA2SC]
    XElement elementNodeDATA2SC = docXmlWorld.Element("DATA2SC");
    //Get the first child => [CALL]
    XElement elementNodeCALL = elementNodeDATA2SC.Element("CALL");
    //Get the attribute NTE from [CALL] node 
    string dne = elementNodeCALL.Attribute("NTE").Value;
    Console.Out.WriteLine(dne);