How can i extract XML and use it as a datasource? - asp.net

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;
}

Related

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.

Retrieving a list of Tridion 2009 components with a specific value and schema without using search

I would like to create a .NET page residing on the CMS server that shows all components that are based on a specific Schema(tcm:3-3-8) and from a specific Publication(tcm:0-3-1) including BluePrinted and Localized items, but only if they have the value "http://www.google.com" for the field "URL" in that Schema.
Is this possible, without using the search service as this is rather slow and unreliable?
Your search might be slow because of not indexing the search collection.
You should do indexing the search collection on regular intervals for better and fast results.
That's an expensive operation to do because of the cost of opening each individual component to check the value of a field, but certainly do-able.
Get the schema object
Get a list of components that use this schema (WhereUsed on the schema with filter on ItemType = component)
Open each component and check the value for the field(s), add to a List<Component> if it matches
Display list (possibly using a ASP.NET GridView)
I have not had any chance to test it, but something like this
Common common = new Common();
TDSE tdse = new TDSE();
ListRowFilter ComponentFilter = tdse.CreateListRowFilter();
Schema schema = (Schema)common.getObject("tcm:126-238630-8", ItemType.ItemTypeSchema);
ComponentFilter.SetCondition("ItemType", ItemType.ItemTypeComponent);
ComponentFilter.SetCondition("Recursive", true);
XDocument doc = common.ReadXML(schema.Info.GetListUsingItems(ListColumnFilter.XMLListID, ComponentFilter));
List<Component> MatchedComponents = new List<Component>();
XmlNamespaceManager NS = new XmlNamespaceManager(new NameTable());
NS.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");
NS.AddNamespace("Content", "uuid:4432F3C3-9F3E-45E4-AE31-408C5C46E2BF");
foreach (XElement component in doc.XPathSelectElements("/tcm:ListUsingItems/tcm:Item", NS))
{
Component comp = common.getComponent(component.Attribute("ID").Value);
XDocument compDoc = common.ReadXML(comp.GetXML(XMLReadFilter.XMLReadData));
foreach (XElement compNode in compDoc.XPathSelectElements("/tcm:Component/tcm:Data/tcm:Content/Content:Content/Content:feederUrl", NS))
{
MatchedComponents.Add(comp);
}
}

Read XML from String

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.

Merging xml Data with Infopath Form Design

hi we all know how the infopath is working. when we give details in infopath form the data is stored as XML File. And when we open it the data from XML are merged with infopath form design(template).
I need to show the data which is present in XML with my own designed(template) form in the runtime. My question is how can i read the fields which is in Infopath Form(in .xml). Then only i can design my own form in the runtime.
i dont know if i understood your question correctly, but if you want to display xml data in another form you have to transform the xml or at least include it as a datasource in your own designed form.
public void SaveXML(string filePath, string sourceXpath)
{
XPathNavigator myRoot = MainDataSource.CreateNavigator();
XPathNavigator node = myRoot.SelectSingleNode(sourceXpath, NamespaceManager);
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write(node.OuterXml.ToString());
sw.Flush();
sw.Close();
}
}
//usage: make sure you understand reading a bit about xpath first, and you will easily know what to put here in param2. you can right click on on any node in the datasource tree of your infopath and select "copy xpath" string to clipboard.
SaveXML(_AuditsFolder + "\\" + fname, "/my:AuditForm/my:Audit");

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