linq to XML as a gridview datasource - c#

I'm trying to get all the email nodes for the customers in the sample xml and binding it to a grid. I can't seemt to get past the linq query!
Sample XML:
<group>
<customer>
<email>testing#testing.com></email>
</customer>
<customer>
<email>testing2#testing.com</email>
</customer>
</group>
var query = from result in xml.Elements("customer")
select new
{
email = xml.Element("email").Value
};
gridview1.DataSource = query;
gridview1.DataBind();

Elements() will only get you direct children, therefore, if your xml variable is an XDocument, its only direct children (according to the little sample) are group elements.
Try:
var query = from result in xml.Descendants("customer")
select new { email = result.Element("email").Value };

Related

I want to fetch the data of child node from XML using C# Linq

im trying to get child node data using c# Linq and i successfully fetch the data but not perfect string im getting data
eg "<value>data</value>" like this but i want data eg: "data"
this my code to fetch the data
var format = from data in xml.Descendants("Insurance")
select new
{
Policy = data.Element("CoreDetails").Elements("ReferenceColumn")
.Elements("value")
.Select(x =>x.ToString())
.ToList()
};
XML
<?xml version="1.0" encoding="UTF-8"?>
<Insurance>
<CoreDetails>
<ReferenceColumn type="Array">
<value>Policy number</value>
<value>Address 1</value>
<value>Buidling Prem</value>
</ReferenceColumn>
</CoreDetails>
</Insurance>
You need the InnerText or Value:
var format = from data in xml.Descendants("Insurance")
select new
{
Policy = data.Element("CoreDetails").Elements("ReferenceColumn")
.Elements("value")
.Select(x =>x.InnerText) //.Select(x =>x.Value)
.ToList()
};

How to Display the XML data to a GRIDVIEW

i have this following XML file
<personaldetails>
<name>ravi</name>
<id>1</id>
<branch>CSE</branch>
</personaldetails>
<professionaldetails>
<name>ravi</name>
<age>25</age>
<gender>male</gender>
</professionaldetails>
This is the sample data .so,now when i search with a name "ravi" in textbox it should display both tables i.e; personal and professional.how to do this using DATATABLE and bind it to GRIDVIEW.
Am doing this in ASP.NET using C#
How can we solve this issue using c#
or
can we do this using LINQ QUERIES
You might use Linq To XML with a valid XML. ie:
string sXML = #"<root>
<personaldetails>
<name>ravi</name>
<id>1</id>
<branch>CSE</branch>
</personaldetails>
<professionaldetails>
<name>ravi</name>
<age>25</age>
<gender>male</gender>
</professionaldetails>
</root>";
var prd = XElement
.Parse(sXML)
.Descendants()
.Where(xe => xe.Name=="professionaldetails" && (string)xe.Element("name") == "ravi")
.Select(p => new {
Name = (string)p.Element("name"),
Age = (int?)p.Element("age"),
Gender = (string)p.Element("gender")
}) ;

C# XML linq query

Hi I have the following XML:
<EPICORTLOG>
<POS>
<ClientId>WkStn.90.1</ClientId>
<Id>POS.90.20140819.251.8279</Id>
<StartTime>2014-08-25T05:12:34</StartTime>
<Store>90</Store>
<SysDate>2014-08-19T00:00:00</SysDate>
<TillNo>1</TillNo>
<Time>2014-08-25T05:12:34</Time>
<Tran>1093</Tran>
<WkStn>1</WkStn>
<WORKSTATION>
<IsAutoLock>1</IsAutoLock>
</WORKSTATION>
<TRADE>
<ITEM>
<Class>102499</Class>
<Desc>NIKE RACER</Desc>
<FinalPrice>82.77</FinalPrice>
<Status>ACTV</Status>
<Style>EV0615</Style>
<Tag>1</Tag>
</ITEM>
</TRADE>
</POS>
</EPICORTLOG>
There are many POS nodes like above in the actual XML. I am trying to fetch the POS node with ID=POS.90.20140819.251.8279 and then the details of Item from that particular node. I have written the following query:
XDocument xdoc = XDocument.Load(XMLFile);
var item = from items in xdoc.Element("EPICORTLOG").Descendants("POS")
where items.Attribute("Id").Value == strSelectedPOSID
select new
{
desc=items.Element("ITEM").Attribute("Desc")
};
But it is not yielding any result for me. Here strSelectedPOSID=POS.90.20140819.251.8279. Please let me know where i am going wrong.
Id and Desc are not an Attributes. they are Elements so you should use
var item = from items in xdoc.Descendants("POS")
where (string)items.Element("Id") == strSelectedPOSID
select new
{
desc = (string)items.Element("ITEM").Element("Desc")
};
I got the value at last!! Following is what i used:
var item = from items in xdoc.Element("EPICORTLOG").Descendants("POS")
where (string)items.Element("Id") == strSelectedPOSID
select new
{
desc = items.Element("TRADE").Element("ITEM").Element("Desc").Value.ToString()
};
Thanks for the inputs.

Matching XElements in an XDocument against a list of names

I have loaded Xml similar to the following into an XDocument
<requestlist>
<request name="Apple" jobtype="radio">
<schedule intervalminutes="1440" daily="true" updateDateTime="2014-08-07T15:43:00Z">
<channel>someData/channel>
<signal>someData</readysignal>
<frequency>someData</frequency>
</schedule>
<file>someData</file>
<file>someData</file>
</request>
</requestlist>
I now want to add a second request that has some info from he first and deletes some unneeded elements e.g.
<request name="newBanana">
<schedule intervalminutes="1440" daily="true" updateDateTime="2014-08-07T15:43:00Z">
</schedule>
<file>someData</file>
</request>
Is there a simple way I can remove the elements using Linq by matching against a list
e.g.
using System.Xml.XPath;
XDocument configXml = XDocument.Parse(theXml)
var oldRequest = configXml.XPathSelectElement(#"/requestlist/request[#name=""Apple""]");
var nodesToRemove = new List<XName>() {"channel", "signal", "radio"};
var newRequest = oldRequest.Elements().Select(e => e.Name).Intersect(nodesToRemove); //OR something
First make your XPath stops at <schedule> element instead of <request> because you'll be removing child of <schedule> here :
var oldRequest = doc.XPathSelectElement(#"/requestlist/request[#name='Apple']/schedule");
Then yes, you can use simple LINQ to remove elements matched a name in list :
var nodesToRemove = new List<XName>() { "channel", "signal", "radio" };
oldRequest.Elements()
.Where(o => nodesToRemove.Contains(o.Name))
.Remove();

Error on converting XML to object using LINQ

I have this xml:
<?xml version="1.0" encoding="utf-8"?>
<Packet>
<Header>
<Id>1234-1234-1234</Id>
</Header>
<Customers>
<Customer>
<Name>Try</Name>
<Age>20</Age>
</Customer>
</Customers>
</Packet>
And this is how I convert it to object:
XDocument xdoc = XDocument.Load(xml);
List<Customer> customers = (from customer in xdoc.Element("Customers").Element("Customer")
select new Customer
{
Name = customer.Element("Name").Value,
Age = customer.Element("Age").Value
}).ToList();
My problem is when I tried to run this code, I got an exception error saying that object reference not set to an instance.
But when i changed my xml to this:
<?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer>
<Name>Try</Name>
<Age>20</Age>
</Customer>
</Customers>
It started working and I am getting the name and age. However, the packet and header is one of the requirements on my xml files. How am I gonna do that?
EDIT:
Thanks for all the solutions! They are all working, but may I know what is the best to use (best practices, etc) Thanks!
You can use Descendants() method to find elements in xml tree.
List<Customer> customers = (from customer in xdoc.Descendants("Customer")
select new Customer
{
Name = customer.Element("Name").Value,
Age = customer.Element("Age").Value
}).ToList();
Change your query source to:
xdoc.Root.Element("Customers").Elements("Customer")
Element method looks for the element on current level, which is the root for XDocument. That's why the query didn't work.
Try changing your LINQ query to:
XDocument xdoc = XDocument.Load(xml);
List<Customer> customers = (from customer in xdoc.Element("Packet").Element("Customers").Element("Customer")
select new Customer
{
Name = customer.Element("Name").Value,
Age = customer.Element("Age").Value
}).ToList();
Because your Customers element is located inside your Packet element.

Categories

Resources