Read XML from String - asp.net

I have data in XML format. I stored it in varchar datatype column. I have retrieved it by using Linq to sql in visual studio 2010. I got xml format data in string variable. now i need read it as a Xml. I need to take value in particular node.
for example,
<Sale>
<LTV>150</LTV>
<CLTV>350</CLTV>
<DLTV>600</DLTV>
</sale>
I NEED TO TAKE CLTV value.

This code should work for you:
using System.Xml;
...
string xmlStr = "<sale><LTV>150</LTV><CLTV>350</CLTV><DLTV>600</DLTV></sale>";
XmlDocument x = new XmlDocument();
x.LoadXml(xmlStr);
MessageBox.Show(x.GetElementsByTagName("CLTV")[0].InnerText);

var value = XDocument.parse("YOUR_XML_STRING").Root.Element("ELEMENT_NAME").Value;

try
var xml = XElement.Parse("your xml");
//Gives you the value of the CLTV node
xml.Descendants("CLTV").FirstOrDefault().Value;
To change the value
xml.Descendants("CLTV").FirstOrDefault().Value = "1";
//Save to disk
xml.Save({stream or file location});
//Get a string back
xml.ToString();
Descendants will give you a list of XElements that you can enumerate or by doing FirstOrDefault you will get the first one it finds or an empty Element.

Related

How to get string from formatted url in asp.net c#

Suppose We are on the page www.abc.com/apple-store
then how to get string apple-store in asp C# code.
to store into another variable.
You can use string.last() to extract it.
string lastPartUrl =HttpContext.Current.Request.Url.AbsoluteUri.Split('/').Last();
You should use the Request.RawUrl property. See more details here.
Alternatelly you can also use the Request.Url (see here) property to get different parts of the current URL. For example you will get the same result using Request.Url.LocalPath.
You can get the url in a string variable. Further you can implement the below logic which will save the value in a variable.
string str = "www.abc.com/apple-store";
string result = "";
int i= 0;
int len = str.Length;
//Get the index of the character
i = str.IndexOf('/');
//store the result in the variable
result = str.Substring(i+1,len-i-1);
Console.WriteLine("Resultant:- {0}", result);`
Hope this helps a bit.

Accessing the query string value using ASP.NET

I have been trying to find the question to my answer but I'm unable to and finally I'm here. What I want to do is access the value passed to a webpage (GET, POST request) using asp.net. To be more clear, for example:
URL: http://www.foobar.com/SaleVoucher.aspx?sr=34
Using asp.net I want to get the sr value i.e 34.
I'm from the background of C# and new to ASP.NET and don't know much about ASP.NET.
Thanx.
Can you refer to this QueryString
Here he says how to access the query string using:
Request.Url.Query
That is not called a Header, but the Query String.
the object document.location.search will contain that and the javascript to get any query string value based on the key would be something like:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
code from other question: https://stackoverflow.com/a/901144/28004

Extracting userid from Inbound headers

I have to read element from Inbound Header...
I am assigning inbound header using WCF.InboundHeaders to a string....
now my problem is my inbounde header is looking like this
InboundHeaders
<headers><s:userid xmlns:s="http://www.w3.org/2003/05/soap-envelope">testuser</s:userid>
<s:applicationid xmlns:s="http://www.w3.org/2003/05/soap-envelope">assistworkerweb</s:applicationid>
<a:Action s:mustUnderstand="1" xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">http://Request</a:Action><a:To s:mustUnderstand="1" xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
Now i need to extract user id from it ..how to extract user id from it..
You haven't mentioned where or how your string is stored (that is populated with your WCF.InboundHeaders), however I would use a simple fragment of XPath to extract the UserId. If you were extracting this using a C# helper, you could do something along the lines of (note, this is untested, however its pretty much there):
XmlDocument doc = new XmlDocument();
doc.Load([WCF.InboundHeaders Xml Fragment]);
// Create an XmlNamespaceManager to add 'soap-envelope' namespace
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
// Select the UserId
XmlNode userId = doc.SelectSingleNode("/headers/s:userid", nsmgr);
Console.WriteLine(userId.InnerXml);
You may also want to serialize the Xml fragment into a .Net object and retrieve the UserId in that manner.

How can i extract XML and use it as a datasource?

I am using asp.net VB and I have an XML file containing a set of data, I would like to use it in something like a datalist and where usually you would use a database i would like to use the XML file to produce the information.
Does anyone know how to do this, i have read about transform files but surely i will format the information in the control?
The file has multiple records so in some cases i would need to perform queries on the information through the datasource.
I would maybe look into XML serialization and de-serialization. Using de-serialization you could read your XML into a List(T) object containing a list of your own class objects and use that as a data source for your application.
Heres a link that you may find useful:
http://msdn.microsoft.com/en-us/library/ms731073.aspx
Hope this helps.
Dim ds As New DataSet()
ds.ReadXml(MapPath("data.xml"))
First you have to parse the XML and store that into custom C# object or you can directly pass the XML to your stored procedure and do the codding there for saving it into DB.
Passing the xml to stored procedure and manipulating it there is bit difficult so what I suggest is to parse it in C# and then get a custom object. Once you get it you can do whatever you want to.
Below is the sample code that parse a XML file and generate a custom C# object from it.
public CatSubCatList GenerateCategoryListFromProductFeedXML()
{
string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);
XDocument xDoc = XDocument.Load(path);
XElement xElement = XElement.Parse(xDoc.ToString());
List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
{
Code = Convert.ToString(d.Element("CategoryCode").Value),
CategoryPath = d.Element("CategoryPath").Value,
Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
}).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();
CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);
return catSubCatList;
}

How to specify the namespace when referencing a table in a dataset

I'm loading data into a DataSet from an XML file using the ReadXml method. This results in two tables with the same name. One of the tables has a namespace and the other doesn't. I'm trying to reference the table with the namespace. Can anyone tell me how to do this?
Dim reader As XmlTextReader = New XmlTextReader(strURL)
Dim city as string = ""
Dim ds As DataSet = New DataSet()
ds.Namespace = "HomeAddress"
ds.ReadXml(reader)
city = ds.Tables("Address").Rows(0).Item(2).ToString()
From MSDN: DataSet.Namespace
The Namespace property is used when
reading and writing an XML document
into the DataSet using the ReadXml,
WriteXml, ReadXmlSchema, or
WriteXmlSchema methods.
The namespace of an XML document is
used to scope XML attributes and
elements when read into a DataSet. For
example, if a DataSet contains a
schema that was read from a document
with the namespace "myCompany," and an
attempt is made to read data only from
a document with a different namespace,
any data that does not correspond to
the existing schema is ignored.
The following example sets the Prefix
before calling the ReadXml method.
private void ReadData(DataSet thisDataSet)
{
thisDataSet.Namespace = "CorporationA";
thisDataSet.Prefix = "DivisionA";
// Read schema and data.
string fileName = "CorporationA_Schema.xml";
thisDataSet.ReadXmlSchema(fileName);
fileName = "DivisionA_Report.xml";
thisDataSet.ReadXml(fileName);
}
I cant see from the example you gave, but unless you set your prefix before you load, you wont be able to read data that doesn't correspond to the existing schema.
I found the answer. You can pass in the namespace as the second parameter. I guess I didn't notice this particular overload in Intellisense.
ds.Tables("Address", "HomeAddress").Rows(1).Item(2).ToString()

Resources