How to fetch specific data from XML using C# - c#

I'm trying to fetch specific data from a Xml file to display in a textbox. My Xml file name as "test.xml" has following code
<?xml version="1.0" encoding="utf-8" ?>
<Body>
<Context>
<PageNo>a87</PageNo>
<Verse>"Do it right"</Verse>
</Context>
</Body>
My C# code is below: Edited to reflect recent chnages
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace learn2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pageid1();
}
private void pageid1()
{
textBox1.Clear();
XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
var pagenoNodeList = doc.SelectNodes("Body/Context/PageNo");
var pageNoNode = pagenoNodeList[0]; // To select the first node
var text = pageNoNode.InnerText; // Gets the text value inside the node
textBox1.Text = text;
} }
}
I highly appreciate any help. Thanks

You need to identify the node you are looking for, as SelectNodes returns a System.Xml.XmlNodeList, and then get the value of InnerText:
var pagenoNodeList = doc.SelectNodes("Body/Context/PageNo");
var pageNoNode = pagenoNodeList[0]; // To select the first node
var text = pageNoNode.InnerText; // Gets the text value inside the node
textBox1.Text = text;

Related

How do I get SOAP xml file data using LINQ and display it in a form's text box? C#

How do I do it?
This is the SOAP XML file
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2001/12/soap-envelope" soapenv:encodingStyle="http://www.w3.org/2001/12/soap-encoding" >
<soapenv:Body xmlns:lle="http://www.aab.org/logevents" >
<lle:Events>
<lle:eventid>ID1</lle:eventid>
<lle:tweet>
<lle:text>This is some tweet in my day</lle:text>
<lle:location>
<lle:lat>66</lle:lat>
<lle:long>77</lle:long>
</lle:location>
<lle:datetimestamp>datetimestamp</lle:datetimestamp>
</lle:tweet>
</lle:Events>
</soapenv:Body>
</soapenv:Envelope>
And this is my C# code, it doesn't display anything in the text box, I have tried adding the "lle:" in front of "Event" and its Descendants like:
.Descendants("lle:Events")
select events.Element("lle:eventid").Value;
but apparently it doesn't work, and there's lots of errors, so I changed it back
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace Xmltest
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
XDocument xmlDocument = new XDocument();
IEnumerable<string> id = from events in XDocument.Load(#"C:\Users\Jack\source\repos\xmltest\Xmltest\XmlFile.xml")
.Descendants("Events")
select events.Element("eventid").Value;
this.txtBox1.Text = id.FirstOrDefault();
}
}
}
but it worked perfectly fine with normal xml file below
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Customers>
<Customer ID="101">
<Name>Robert</Name>
<Mobile>9820098200</Mobile>
<Location>Bangladesh</Location>
<Address>XYZ</Address>
</Customer>
<Customer ID="102">
<Name>Kate</Name>
<Mobile>983452342</Mobile>
<Location>Japan</Location>
<Address>ABC</Address>
</Customer>
<Customer ID="103">
<Name>Catherine</Name>
<Mobile>123456785</Mobile>
<Location> London</Location>
<Address>CDE</Address>
</Customer>
<Customer ID="10004">
<Name>Richard</Name>
<Mobile>899990012</Mobile>
<Location>France</Location>
<Address>MNO</Address>
</Customer>
</Customers>
I believe that's because you are using strings to refer to element. You should use XName, e.g. instead of "Events" or "eventid" use:
var events = XName.Get("Events", "http://www.aab.org/logevents");
var eventId = XName.Get("eventid", "http://www.aab.org/logevents");
You can use below powershell snippet for a quick test:
$x = [System.Xml.Linq.XDocument]::Load("C:\Users\Jack\source\repos\xmltest\Xmltest\XmlFile.xml")
$evtName = [System.Xml.Linq.XName]::Get("Events", "http://www.aab.org/logevents")
$idName = [System.Xml.Linq.XName]::Get("eventid", "http://www.aab.org/logevents")
$x.Descendants($evtName).Element($idName).Value | Write-Host
You have to handle the Xml Namespace. You can do this by querying with XName, instead of with a string:
using System;
using System.Linq;
using System.Xml.Linq;
public class Program
{
public static void Main()
{
var inXml = #"<soapenv:Envelope xmlns:soapenv=""http://www.w3.org/2001/12/soap-envelope"" soapenv:encodingStyle=""http://www.w3.org/2001/12/soap-encoding"" >
<soapenv:Body xmlns:lle=""http://www.aab.org/logevents"" >
<lle:Events>
<lle:eventid>ID1</lle:eventid>
<lle:tweet>
<lle:text>This is some tweet in my day</lle:text>
<lle:location>
<lle:lat>66</lle:lat>
<lle:long>77</lle:long>
</lle:location>
<lle:datetimestamp>datetimestamp</lle:datetimestamp>
</lle:tweet>
</lle:Events>
</soapenv:Body>
</soapenv:Envelope>";
var eventIdsXName = XName.Get("eventid", "http://www.aab.org/logevents");
var eventIds = XDocument.Parse(inXml)
.Descendants(eventIdsXName)
.Select(i => i.Value);
foreach(var eventId in eventIds){
Console.WriteLine($"Value: {eventId}");
}
}
}
Output:
Value: ID1
See:
https://dotnetfiddle.net/IEdwz1

C# XML Query to display Exception Error [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I attempting to display some XML results based on a user submitted xml document and user submitted XPath syntax into a rich text box. My issue is a I keep getting the error:
An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication1.exe
Additional information: Object reference not set to an instance of an object.
Here is my code below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Collections.Generic;
using System.ComponentModel;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML |*.xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(ofd.FileName);
richTextBox1.Text = xDoc.SelectSingleNode(textBox1.Text).InnerText;
}
}
}
}
Change this line
richTextBox1.Text = xDoc.SelectSingleNode(textBox1.Text).InnerText;
to
XmlNode node = xDoc.SelectSingleNode(textBox1.Text);
if(node != null)
richTextBox1.Text = node.InnerText;
And investigate why node is null.

C# XmlDocument for grabbing API specific data?

I am trying to grab the specific value of an attribute in:
http://data.alexa.com/data?cli=10&dat=snbamz&url=bing.com
<SD>
<POPULARITY URL="bing.com/" TEXT="16" SOURCE="panel"/>
<REACH RANK="16"/>
<RANK DELTA="-7"/>
<COUNTRY CODE="US" NAME="United States" RANK="9"/>
</SD>
</ALEXA>
I want to grab the value of
I have the current Console Code for this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string url = "http://data.alexa.com/data?cli=10&dat=snbamz&url=bing.com";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(url);
XmlNode root = xmldoc.SelectSingleNode("//#RANK");
//XmlNamespaceManager xnm1 = new XmlNamespaceManager(xmldoc.NameTable);
//XmlNodeList nList1 = xmldoc.SelectNodes("//#RANK", xnm1);
Console.WriteLine(root.ToString());
Console.ReadLine();
}
}
}
But when I run it, I receive the following message in return:
System.Xml.XmlAttribute
What am I doing wrong?
Try changing:
Console.WriteLine(root.ToString());
to:
Console.WriteLine(root.Value);
Hope that helps.

Read from a XML file to an Array node by node in C#

The XML file is like this,There are about 20 Nodes(modules) like this.
<list>
<module code="ECSE502">
<code>ECSE502</code>
<name>Algorithms and Data structures</name>
<semester>1</semester>
<prerequisites>none</prerequisites>
<lslot>0</lslot>
<tslot>1</tslot>
<description>all about algorythms and data structers with totorials and inclass tests</description>
</module>
</list>
I did the following code. But when I debugged it it even didn't went inside to foreach function.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ModuleEnrolmentCW
{
class XMLRead
{
public string[] writeToXML(string s)
{
string text = s;
string[] arr = new string[6];
XmlDocument xml = new XmlDocument();
xml.Load("modules.xml");
XmlNodeList xnList = xml.SelectNodes("list/module[#code='" + text + "']");
foreach (XmlNode xn in xnList)
{
arr[0] = xn.SelectSingleNode("code").InnerText;
arr[1] = xn.SelectSingleNode("name").InnerText;
arr[2] = xn.SelectSingleNode("semester").InnerText;
arr[3] = xn.SelectSingleNode("prerequisites").InnerText;
arr[4] = xn.SelectSingleNode("lslot").InnerText;
arr[5] = xn.SelectSingleNode("tslot").InnerText;
}
return arr;
}
}
}
Please tell me where is the wrong??
Here is the rest of the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ModuleEnrolmentCW
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string selected;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
XMLRead x = new XMLRead();
selected = (string)listBox1.SelectedItem;
string[] arr2 = x.writeToXML(selected);
label11.Text = arr2[0];
}
}
}
Make sure you are specifying correct path for your xml file.
It is working for me.
This line:
XmlNodeList xnList = xml.SelectNodes("list/module[#code='" + text + "']");
should read:
XmlNodeList xnList = xml.SelectNodes("list/module"); //Does not answer full scope of the question
Edit following a reread of the question:
The OP's code works fine in my tests. Either the file path is not correct, or the the string s passed into text matches the case of the Code value by which you are reading the nodes.
The SelectNodes XPath as you have it is case sensitive.
You appear to be working with XPath V1.0 which doesn't appear to support out of the box case insensitivity if that's a issue. See this link for a way to perform case insensitive XPath searches: http://blogs.msdn.com/b/shjin/archive/2005/07/22/442025.aspx
See also this link: case-insensitive matching in xpath?
Your code is correct, if the input is really the one you shown, and s point to an actual present code. Since you are pointing the file by a relative path, ensure you are loading the file you really expect.
Found the error. I was passing a wrong value to writeToXML method. Insted of passing code, I have passed name

Rss Reader in visual C# express edition

Hi I am trying to create a RSS reader in visual C# express. I need to read the rss feed into a text box when the form loads. I have never worked with RSS feeds before and all the examples I have come across are done in visual studio and it seems that I cant use this:
(XmlReader reader = XmlReader.Create(Url))
This is what I have got so far. It doesn't work.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var s = RssReader.Read("http://ph.news.yahoo.com/rss/philippines");
textBox1.Text = s.ToString();
}
public class RssNews
{
public string Title;
public string PublicationDate;
public string Description;
}
public class RssReader
{
public static List<RssNews> Read(string url)
{
var webResponse = WebRequest.Create(url).GetResponse();
if (webResponse == null)
return null;
var ds = new DataSet();
ds.ReadXml(webResponse.GetResponseStream());
var news = (from row in ds.Tables["item"].AsEnumerable()
select new RssNews
{
Title = row.Field<string>("title"),
PublicationDate = row.Field<string>("pubDate"),
Description = row.Field<string>("description")
}).ToList();
return news;
}
}
I am not sure what I should do. Please help.
Well your code is working as expected, since you are returning a List of RSSNews items, but you are assigning it to the textbox in a wrong way. Doing textBox1.Text = s.ToString(); will give System.Collections.Generic.List.... as a result.
Your method is reading RssNews items from the dataset and return around 23 items against the feed. You need to iterate through these items and display its text in the textbox, or better if you may use GridView or similar control to show these results.
You may try the following code in your Main method:
var s = RssReader.Read("http://ph.news.yahoo.com/rss/philippines");
StringBuilder sb = new StringBuilder();
foreach (RssNews rs in s)
{
sb.AppendLine(rs.Title);
sb.AppendLine(rs.PublicationDate);
sb.AppendLine(rs.Description);
}
textBox1.Text = sb.ToString();
This will create a string for each item of RssNews and will display the result in textBox1.

Categories