不能用c# XPath获取属性值

本文关键字:属性 获取 XPath 不能 | 更新日期: 2023-09-27 18:12:34

我已经花了这么多时间了,仍然不能得到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>

不能用c# XPath获取属性值

您能试一下这个代码吗?

我已经检查过了,它是工作的

    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);

    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);

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

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

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