简体   繁体   中英

Get data from an XML file in a Button_Click event

I'm trying to get data from an XML file with this code:

private void button1_Click(object sender, EventArgs e)
{
    XDocument doc = XDocument.Load(@"C:\..\WindowsFormsApp10\stores.xml");
    var xpath = "//store[Color='Pink']";
    var result = doc.XPathEvaluate(xpath);
    textBox1.Text = result.ToString();
}

My XML is:

<stores>
    <store rollNumer="170">
        <Name>Jonh</Name>
        <Color>Pink</Color>
        <Sell>Sugar</Sell>
    </store>

    <store rollNumer="120">
        <Name>Tedy</Name>
        <Color>Brown</Color>
        <Sell>Rice</Sell>
    </store>
</stores>            <!-- Added by edit -->

But it gives me this error:

System.Xml.XPath.XPathEvaluator+EvaluateIterator>d__1`1[System.Object]

What can I do?

Its printing, System.Xml.XPath.XPathEvaluator+EvaluateIterator>d__1 1[System.Object]` because you are printing the object. Using ToString() on an object does not print all properties of the object; instead, it prints the type of the object with ToString() method.

The XPath you are using is looking for Color whose 'something' is Pink when you should be checking the text() of the Color to be Pink.

This will do the trick,

XDocument doc = XDocument.Load(filename);
var xpath = "//store/Color[text() = 'Pink']";
var result = ((IEnumerable)doc.XPathEvaluate(xpath)).Cast<XElement>().FirstOrDefault();
Console.WriteLine(result.Value);

Prints the following output:

Pink

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