• 0

Parse XML with LINQ not reading values


Question

Hi, we're in the process of rewriting one of our webapps to .NET 4.5 and we are trying to use LINQ to parse our XML for outputting. I have the following XML and C# below, but it writes out nothing, I have a feeling it maybe something simple I've overlooked in the code, any help/guidance on LINQ would be appreciated.
 

XML

<?xml version="1.0" encoding="utf-8"?>
<Items>
  <Status>OK</Status>
  <ListOf>
    <Item>
      <Name>Test 1</Name>
      <Description>Test of a really long description</Description>
      <Picture>http://test.com/test.jpg</Picture>
      <Price>Free</Price>
    </Item>
    <Item>
      <Name>Test 2</Name>
      <Description>Test of a really long description</Description>
      <Picture>http://test.com/test2.jpg</Picture>
      <Price>Free under 5s</Price>
    </Item>
  </ListOf>	
</Items>

C#

System.Collections.Specialized.NameValueCollection _query = new System.Collections.Specialized.NameValueCollection() {
{"mode", "test"}
};

using (var wclient = new WebClient())
{
	var result = wclient.UploadValues("http://{XML_ADDRESS_REMOVED}", _query);
	string xml = System.Text.Encoding.UTF8.GetString(result);

	XDocument doc = XDocument.Parse(xml);
	var data = from item in doc.Descendants("Item")
			   select new
			   {
				   Name = item.Element("Name").Value.ToString(),
			   };

	foreach (var item in data)
	{
		Response.Write("Title: " + item.Name + "<br />");
	}
}
Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

I tested the "LINQ" part of the code and it works fine using the provided example XML data. Step into the code and make sure you're getting the correct response from the server.

 

Code used to test:

private void button1_Click(object sender, EventArgs e)
        {
            XDocument doc = XDocument.Parse(File.ReadAllText("data.xml"));
 
            var data = from item in doc.Descendants("Item")
                        select new
                        {
                            Name = item.Element("Name").Value.ToString(),
                        };
 
            foreach (var item in data)
            {
                listBox1.Items.Add("Title: " + item.Name + "<br />");
            }
        }

Output in listBox1:

Title: Test 1<br />
Title: Test 2<br />
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.