简体   繁体   中英

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

如果您的整个XML仅包含此节点,则可以为xml.DocumentElement.Attributes["value"].Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM