我一直试图将xml节点的值拉入一个字符串。以下是XML的外观:

<currentvin value="1FTWW31R08EB18119" />

我好像想不出如何抓住这个价值。顺便说一下,我没有写这个XML。到目前为止,我尝试了几种方法,包括:
    public void xmlParse(string filePath)
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(filePath);
        XmlNode currentVin = xml.SelectSingleNode("/currentvin");
        string xmlVin = currentVin.Value;
        Console.WriteLine(xmlVin);
    }

这不管用。然后我试着:
    public void xmlParse(string filePath)
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(filePath);
        string xmlVin = xml.SelectSingleNode("/currentvin").Value;
        Console.WriteLine(xmlVin);

    }

但这也不管用。我收到一个空引用异常,声明对象引用未设置为对象的实例。有什么想法吗?

最佳答案

我认为您将xmlnode类的Value属性与名为“value”的xml属性混淆了。
值是XML中的一个属性,因此请将xpath查询修改为

xml.SelectSingleNode("/currentvin/@value").Value

或者使用所选xmlnode的Attributes集合。

10-07 19:04
查看更多