Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Tuesday, August 9, 2011

Query Xml File with Namespace using XPath



We all know how to get value from xml file in .net but we face issue when there is a namespace with that xml file.

When a xml file contains a namespace then you will have to do some extra efforts to retrieve its value.

Lets say my xml is like:



Videos
119150

207463
somepath
sometitle
somelink
...

http://someurl/standard-and-poors-india-connection/207463

Tue, 09 Aug 2011 6:26:48 IST
1312894608




Now i wants to access value of "url" attribute of "media:thumbnail" tag, so to get it you will have to do :

Dim path As String = "http://api.flickr.com/services/feeds/photoset.gne?set=72157604607980332&nsid=51374889@N00&lang=en-us&format=rss_200_enc"
        Dim xmldoc As New XmlDocument()
        xmldoc.Load(path)
        Dim xnm As New XmlNamespaceManager(xmldoc.NameTable)
        xnm.AddNamespace("media", "http://search.yahoo.com/mrss/")
        Dim nList As XmlNodeList = xmldoc.SelectNodes("//item/media:thumbnail/@url", xnm)

        For Each xNode As XmlNode In nList
            ListBox1.Items.Add(xNode.InnerText)
            TextBox1.Text += TextBox1.Text + xNode.InnerText + vbNewLine
        Next


Now comes to original problem for which i have done google for 2-3 hours and then finally i got the answer.

Problem: I have got a repeater and i wants to show this xml values in it. now 1 option is that you can convert it to a datatable and easily use it.. but it will be extra process to you application. so now we wants to show xml directly to the repeater... to do so see below code:

In code behind file:
XmlDataSource xds = new XmlDataSource();
xds.XPath = "rss/channel/item";
xds.DataFile = sourceXml;// you can write xml path here.
myrpt.DataSource = xds;
myrpt.DataBind();

Now in .aspx file write below code:
< asp:Repeater ID="myrpt" runat="server" >
                < ItemTemplate >
                    < li >
                        < div class="multi_div" >
                            < img src='< %#XPath("*[local-name()='thumbnail' and namespace-uri()='http://search.yahoo.com/mrss/']/@url")% >' class="imgbdr" / >< div class="multi_blkstrip" >
                                < p class="float_l" >
                                    < img src="images/video_icon.gif" / >< /p >
                                < p class="float_r" >
                                    < %#XPath("title")% >< /p >
                            < /div >
                        < /div >
                        < p class="vidcap" >
                            < a href="#" class="fn fl" >< %#XPath("title")% >< /a >< /p >
                    < /li >
                < /ItemTemplate >
            < /asp:Repeater >

so this is the main line (solution):

< %#XPath("*[local-name()='thumbnail' and namespace-uri()='http://search.yahoo.com/mrss/']/@url")% >'

Compiled By: Rajesh Rolen

Read More

Thursday, May 5, 2011

Write xml text on aspx page

you can use below code to write xml file data (string) on page.

first of all remove all content from aspx page except "page" directive.

 XmlDocument doc = new XmlDocument();
 doc.LoadXml(stringxml);
 Response.Clear(); //optional: if we've sent anything before
Response.ContentType = "text/xml"; //must be 'text/xml'
Response.ContentEncoding = System.Text.Encoding.UTF8; //we'd like UTF-8
doc.Save(Response.Output); //save to the text-writer 
Response.End(); 
Read More

Wednesday, January 19, 2011

Read XML from network/ static ip with credentials

When you wants to read/get xml from network or from static ip on web then you would required to validate your credentials for that. below is example from which you can learn that how to access xml from another system with validating credentials.

public XmlDocument getXML()
{
string fileName = "123.22.23.2//folderName//xmlName.xml";
        Uri myUrl = new Uri("file://" + fileName);

        FileWebRequest request = (FileWebRequest)WebRequest.Create(myUrl);
        byte[] authBytes = Encoding.UTF8.GetBytes(("myuserName" + ":" + "MyPassword").ToCharArray());
        request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);
        WebResponse response = request.GetResponse();
        Stream strm = response.GetResponseStream();
        StreamReader sr = new StreamReader(strm, System.Text.Encoding.Default);
        XmlDocument xdoc = new XmlDocument();
        xdoc.LoadXml(sr.ReadToEnd());
        return xdoc;
}
Read More

Tuesday, October 5, 2010

Read config file using XML reader

The best way is to use System.Configuration.ConfigurationManager.AppSettings; to retrive values of webconfig but from xml reader you can also do that:


private void loadConfig()
{

XmlDocument xdoc = new XmlDocument();
xdoc.Load( Server.MapPath("~/") + "web.config");
XmlNode xnodes = xdoc.SelectSingleNode ("/configuration/appSettings");

foreach (XmlNode xnn in xnodes .ChildNodes)
{
ListBox1.Items.Add(xnn.Attributes[0].Value + " = " + xnn.Attributes[1].Value );
}

}
Read More

Thursday, September 23, 2010

Load XML using javascript [works with all browser]

When ever we wants to load and parse xml using javascript. we face a issue most of time is that the script works with one browser but not works with other.
Below script will work on all browsers including [safari,mizila firefox, crome]:


function loadxml() {
var xmlFeed = "xmldata/wfc20100915.xml";
if (window.ActiveXObject) {
var errorHappendHere = "Check Browser and security settings";
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(xmlFeed);
}
else if (window.XMLHttpRequest) {
var errorHappendHere = "Error handling XMLHttpRequest request";
var d = new XMLHttpRequest();
d.open("GET", xmlFeed, false);
d.send(null);
xmlDoc = d.responseXML;
} else {
var errorHappendHere = "Error.";
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async = false;
xmlDoc.load(xmlFeed);
}


var tmp = readXML();

return tmp;
}
//below code is to read xml
function readXML() {

var labels = xmlDoc.getElementsByTagName('node');
arr = new Array();
var counter = 0;
for (i = 0; i < labels.length/ 10; i++) {
{
if (labels[i].childNodes.length >= 9) {
arr[counter] = new Array(5);
arr[counter][0] = parseFloat(labels[i].childNodes[1].textContent);
arr[counter][1] = parseFloat(labels[i].childNodes[3].textContent);
arr[counter][2] = parseFloat(labels[i].childNodes[5].textContent);
arr[counter][3] = parseFloat(labels[i].childNodes[7].textContent);
arr[counter][4] = parseFloat(labels[i].childNodes[9].textContent);
counter++;
}

}

return arr;

}


Solutions by: Rajesh Rolen

Read More

Tuesday, December 29, 2009

Use HostelsClub Search Web-Service in ASP.NET

HostelsClub is one of the worlds larges search engine to search hotels, hostels, rooms and also provide booking of it. so if you want to integrate such a functionality in your website then you will have to take authentication from hostelclub and he will provide you Authentication id and password for Test (free of cost) and later you can upgrade to "Production" version (it will take some percentage in booking cost's profit).

HostelsClub provides you API Library and sample application in PHP to get connect with hostelsclub. But they don't have any API Library or application in ASP.NET. so if you want to do this, below sample can help you.

Through this sample you can PING the hostelsclub web-service search engine.


string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\ping.xml"));//this is your xml file which u want to send to hostelsclub for ping
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
//string sendString = HttpUtility.UrlEncode(xmlData);

byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;

using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}

HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object

XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();


}
}

//===================PING.XML=======================
< ?xml version="1.0" encoding="UTF-8"? >
< OTA_PingRQ xmlns="http://www.opentravel.org/OTA/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_PingRQ.xsd" TimeStamp="2009-12-28T11:43:43-05:00" Target="Test" Version="1.006" PrimaryLangID="en" EchoToken="1" >
< EchoData >Hello World< /EchoData >
< /OTA_PingRQ >

Read More

How to send/recive XML file through HTTP Post

If you want to send a XML file through HTTP using POST to any web service which may /may not build in .net. this example can help u:
string targetUri = "http://www.targeUrl.com";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\myfile.xml"));//xml file which you want to send
string formParameterName = "OTA_request";//request type
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
//string sendString = HttpUtility.UrlEncode(xmlData);

byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;

using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}

HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object

XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();


}
}
Read More

Friday, July 31, 2009

Data into DataGridView from XML file

In this article we are going to know how to get data in DataGridView from XML file.
now we create an XML file.

Create an XML file:

< ?xml version="1.0" encoding="utf-8" ? >
< bookstore >
< book >
< title > The < /title >
< price > 8.99 < /price >
< genre > autobiograph < /genre >
< publicationdate > 1981 < /publicationdate >
< ISBN > 1-861003-11- < /ISBN >
< PageSize > 500 < /PageSize >
< /book >

< book >
< title > The Confiden < /title >
< price > 11.99 < /price >
< genre > novel < /genre >
< publicationdate > 1967 < /publicationdate >
< ISBN > 0-201-63361- < /ISBN >
< /book >

< book >
< title > The Gorgias < /title >
< price > 9.99 < /price >
< genre > philosophy < /genre >
< publicationdate > 1991 < /publicationdate >
< ISBN > ss1-861001-57- < /ISBN >
< PageSize > 600 < /PageSize >
< /book >
< /bookstore >

Create the window application:
There are the following steps for creating the window application.

Step 1: Create new project.

Step 2: Drag and drop DataGridView control from the toolbox on form, and fill all required properties.

Step 3: Add the following namespace to page (form):

using System.Data.SqlClient;
using System.Xml;

Step 4: Write the code on the form load event.

For Example:

Form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Xml;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
XmlDataDocument xmlDatadoc = new XmlDataDocument();
xmlDatadoc.DataSet.ReadXml("C:\\books.xml");
DataSet ds = new DataSet("Books DataSet");
ds = xmlDatadoc.DataSet;
dataGridView1.DataSource = ds.DefaultViewManager;
dataGridView1.DataMember = "Book";
}
}
}
Read More

Export Data Grid Content to an XML File

we can use the RenderControl method to extract the content into an .xml file from datagridview.
your Data Grid is not associated with any dataset.and not using any XML support functions

The following code explains:


ArrayList al = new ArrayList();
for(int i=0;i<=10;i++)
{
al.Add(i+"");
}
DataGrid1.DataSource=al;
DataGrid1.DataBind();
Response.Clear();
Response.AddHeader("content-disposition","fileattachment;filename=xmltest.xml");
Response.ContentType="text/xml";

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
DataGrid1.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
Read More
Powered By Blogger · Designed By Seo Blogger Templates