How to Display the XML data to a GRIDVIEW - c#

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

Related

How to get enclosure url with XElement C# Console

I read multiple feed from many sources with C# Console, and i have this code where i load XML From sources:
XmlDocument doc = new XmlDocument();
doc.Load(sourceURLX);
XElement xdoc = XElement.Load(sourceURLX);
How to get enclosure url and show as variable?
If I understand your question correctly (I'm making a big assumption here) - you want to select an attribute from the root (or 'enclosing') tag, named 'url'?
You can make use of XPath queries here. Consider the following XML:
<?xml version="1.0" encoding="utf-8"?>
<root url='google.com'>
<inner />
</root>
You could use the following code to retrieve 'google.com':
String query = "/root[1]/#url";
XmlDocument doc = new XmlDocument();
doc.Load(sourceURLX);
String value = doc.SelectSingleNode(query).InnerText;
Further information about XPath syntax can be found here.
Edit: As you stated in your comment, you are working with the following XML:
<item>
<description>
</description>
<enclosure url="blablabla.com/img.jpg" />
</item>
Therefore, you can retrieve the url using the following XPath query:
/item[1]/enclosure[1]/#url
With xml like below
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>title</title>
<link>https://www.link.com</link>
<description>description</description>
<item>
<title>RSS</title>
<link>https://www.link.com/xml/xml_rss.asp</link>
<description>description</description>
<enclosure url="https://www.link.com/media/test.wmv"
length="10000"
type="video/wmv"/>
</item>
</channel>
</rss>
You will get url by reading attribute
var document = XDocument.Load(sourceURLX);
var url = document.Root
.Element("channel")
.Element("item")
.Element("enclosure")
.Attribute("url")
.Value;
To get multiple urls
var urls = document.Descendants("item")
.Select(item => item.Element("enclosure").Attribute("url").Value)
.ToList();
Using foreach loop
foreach (var item in document.Descendants("item"))
{
var title = item.Element("title").Value;
var link = item.Element("link").Value;
var description = item.Element("description").Value;
var url = item.Element("enclosure").Attribute("url").Value;
// save values to database
}

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

Getting attributes from same-named XDocument elements using LINQ

I've been coding a program that stores employee data using XDocument:
<!-- School Employee Data -->
<SchoolData storeName="mikveIsrael" location="mikve">
<employee id="1">
<personalInfo>
<name>Ilan Berlinbluv</name>
<zip>58505</zip>
</personalInfo>
<employeeInfo>
<salary>5000</salary>
<id>1</id>
</employeeInfo>
</employee>
<employee id="2">...</employee>
</SchoolData>
I want my program to read every employee id attrib, but I don't know how to do so. Instead, I tried doing this:
var ids = from idz in doc.Descendants("SchoolData")
select new
{
id1 = idz.Element("employee").Attribute("id").Value
};
where doc is the XDocument var. It returns just the first one, but I want it to return an array or List<string>, I just don't know how to iterate through all the same-named employee elements.
XDocument doc = XDocument.Parse(xml);
List<string> ids = doc.Descendants("employee")
.Select(e => e.Attribute("id").Value)
.ToList();
This may helps:
var xDoc = XDocument.Load(path);
var result = xDoc.Descendants("employee")
.SelectMany(i => i.Attribute("id").Value)
.ToList();

Parse dynamically created XML document in c#

I have to parse an XML document like this:
<?xml version="1.0" encoding="utf-8" ?>
<DialsList>
<Dial>
<Id>123</Id>
<Source>SQL</Source>
<Server>myServer</Server>
<Database>myDB</Database>
<UserName>myUserName</UserName>
<Password>myPassword</Password>
<TableName>myTable</TableName>
<Query>GetAvgForUser</Query>
<Parameters>
<Param1>
<Name>#DialId</Name>
<Type>Int</Type>
</Param1>
<Param2>
<Name>#UserId</Name>
<Type>String</Type>
</Param2>
</Parameters>
</Dial>
<Dial>
<Id>789</Id>
<Source>SQL</Source>
<Server>someServer</Server>
<Database>someDB</Database>
<UserName>someUser</UserName>
<Password>somePwd</Password>
<TableName>someTbl</TableName>
<Query>someQry</Query>
<Parameters>
<Param1>
<Name>#myParam</Name>
<Type>Int</Type>
</Param1>
<Param2>
<Name>#anotherParam</Name>
<Type>String</Type>
</Param2>
</Parameters>
</Dial>
</DialsList>
My application has to read this XML document and form the connection string as well as execute the query/storedprocedure specified in the <Query> node. I have no problems forming the connectionstring. Since it can be any stored procedure and it can have any number of parameters,I cannot figure out a way to parse this XML. The XML will be dynamic - parameters,parameter names,parameter type,etc. and it's not under my control. I have this code so far which works if there's only 1 Parameter(I'm assuming it will be "int"):
XDocument doc = XDocument.Load(xmlFileName);
string dialID = Convert.ToString(DialId);
XElement DialsDoc = (from xml2 in doc.Descendants("Dial") where xml2.Element("Id").Value == dialID select xml2).FirstOrDefault();
dialDataSrc.Source = DialsDoc.Element("Source").Value.ToString();
if (dialDataSrc.Source.ToString() == "SQL")
{
DataSource dialDataSrc = new DataSource();
dialDataSrc.MethodNameIndividual = string.Empty;
dialDataSrc.MethodNameGroup = string.Empty;
dialDataSrc.Server = DialsDoc.Element("Server").Value.ToString();
dialDataSrc.Database = DialsDoc.Element("Database").Value.ToString();
dialDataSrc.Username = DialsDoc.Element("UserName").Value.ToString();
dialDataSrc.Password = DialsDoc.Element("Password").Value.ToString();
dialDataSrc.TableName = DialsDoc.Element("TableName").Value.ToString();
dialDataSrc.Query = DialsDoc.Element("Query").Value.ToString();
dialDataSrc.Parameters = DialsDoc.Element("Parameters").Value.ToString();
}
I then form the connection string and execute the stored procedure.
How do I go about handling this when it's dynamic?
I can't figure out the Type of dialDataSrc but this should get you on your way:
var listOfparameters = DialsDoc
.Element("Parameters")
.Elements()
.Select(p => MyCreateParam((string) p.Element("Name"), (string) p.Element("Type")))
.ToList();
With a little helper method to figure out the DbType etc:
private SqlParameter MyCreateParam(string name, string _type) { ... }

Retrieving Multiple Items from an XML File using LINQ to XML with C#

I'm new to LINQ to XML and I'm having problems writing C# to retrieve multiple items from an XML file, i.e. in the code sample below. I would like to go through the file and retrieve each OrderProduct id=??? and get the information in Quantities and Product. I can retrieve a single order only, but not if more than one is in the file.
This is the C# code I'm using which only retrieves the first order.
xelement = XElement.Load (orderXML);
IEnumerable<XElement> OrderXml = xelement.Elements ();
foreach (var order in OrderXml.Elements ("OrderProducts"))
{
m_productOrderID = order.Element ("OrderProduct").Attribute ("id").Value;
m_productName = order.Element ("OrderProduct").Element ("Product").Element ("Name").Value;
m_productCatalogNumber = order.Element ("OrderProduct").Element ("Product").Element ("CatalogNumber").Value;
m_productQuantity = order.Element ("OrderProduct").Element ("Quantities").Element ("NumberOfCopies").Value;
}
The XML file:
<?xml version="1.0" encoding="utf-16"?>
<OrderXml>
<Order>
<OrderProducts>
<OrderProduct id="569">
<Quantities>
<NumberOfRecipients>1</NumberOfRecipients>
<NumberOfCopies>1</NumberOfCopies>
<TotalUnits>1</TotalUnits>
</Quantities>
<Product id="444">
<Name>Product 1</Name>
<CatalogNumber>20130621-001</CatalogNumber>
</Product>
</OrderProduct>
<OrderProduct id="570">
<Quantities>
<NumberOfRecipients>1</NumberOfRecipients>
<NumberOfCopies>100</NumberOfCopies>
<TotalUnits>100</TotalUnits>
</Quantities>
<Product id="258">
<Name>Product 2</Name>
<CatalogNumber>20130621-002</CatalogNumber>
</Product>
</OrderProduct>
</OrderProducts>
</Order>
</OrderXml>
from op in xdoc.Descendants("OrderProduct")
let q = op.Element("Quantities")
let p = op.Element("Product")
select new {
Id = (int)op.Attribute("id"),
Quantities = new {
NumberOfRecipients = (int)q.Element("NumberOfRecipients"),
NumberOfCopies = (int)q.Element("NumberOfCopies"),
TotalUnits = (int)q.Element("TotalUnits")
},
Product = new {
Id = (int)p.Attribute("id"),
Name = (string)p.Element("Name"),
CatalogNumber = (string)p.Element("CatalogNumber")
}
}
Then getting single order product:
var orderProduct = query.FirstOrDefault(x => x.Id == yourId);
if (orderProduct != null)
// ...
Getting all ids:
var ids = xdoc.Descendants("OrderProduct")
.Select(op => (int)op.Attribute("id"));
BTW Next time provide code which you already have

Categories

Resources