开发者

Get xml node value as string C#

I've been trying to pull the value of the XML node into a string. Here is what the XML looks like:

<currentvin value="1FTWW31R08EB18119" /> 

I can't seem to figure out how to grab that value. I didn't write this XML, by the way. So far I have tried several approaches, including the following:

    public void xmlParse(string filePath)
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(filePath);
       开发者_StackOverflow社区 XmlNode currentVin = xml.SelectSingleNode("/currentvin");
        string xmlVin = currentVin.Value;
        Console.WriteLine(xmlVin);          
    }

Which doesn't work. I then tried:

    public void xmlParse(string filePath)
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(filePath);
        string xmlVin = xml.SelectSingleNode("/currentvin").Value;
        Console.WriteLine(xmlVin);

    }

But that doesn't work either. I am getting a null reference exception stating that Object reference not set to an instance of an object. Any ideas?


I think you're confusing the Value property of the XmlNode class, with an XML attribute named "value".

value is an attribute in your xml so either modify your xpath query to be

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

Or user the Attributes collection of the selected XmlNode.


You are looking for the value of the attribute "value" (that's a handful) not the value of the node itself - so you have to use the Attribute property:

string xmlVin = xml.SelectSingleNode("/currentvin").Attributes["value"].Value;

Or in the first version:

XmlNode currentVin = xml.SelectSingleNode("/currentvin");
string xmlVin = currentVin.Attributes["value"].Value;


If your entire XML contains only this node then it could be xml.DocumentElement.Attributes["value"].Value;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜