Parsing XML using LINQ in c# - c#

In this xml file (http://www.studiovincent.net/list.xml):
<list version="1.0">
<meta>
<type>resource-list</type>
</meta>
<resources start="0" count="4">
<resource classname="Quote">
<field name="name">Vincent</field>
<field name="username">Hill</field>
<field name="age">31</field>
<field name="hair">black</field>
</resource>
<resource classname="Quote">
<field name="name">John</field>
<field name="username">Tedelon</field>
<field name="age">27</field>
<field name="hair">brown</field>
</resource>
<resource classname="Quote">
<field name="name">Michael</field>
<field name="username">Lopez</field>
<field name="age">20</field>
<field name="hair">red</field>
</resource>
<resource classname="Quote">
<field name="name">Frank</field>
<field name="username">Lopez</field>
<field name="age">25</field>
<field name="hair">black</field>
</resource>
</resources>
</list>
using this code:
using System.Xml;
using.System.Xml.Linq;
XmlReader reader = XmlReader.Create("http://www.studiovincent.net/list.xml");
XElement el = XElement.Load(reader);
reader.Close();
var items = el.Elements("resources").Elements("resource").Descendants().DescendantNodes();
var items = from item in el.Elements("resources").Elements("resource").Descendants()
where item.Attribute("name").Value == "name" select item.FirstNode;
foreach (XNode node in items)
{
Console.WriteLine(node.ToString());
}
I have this OUTPUT:
Vincent
John
Michael
Frank
Code working very good, but I need get value 31 which corresponds field name="age" where field name="name" is Vincent. How Can I get this result?

I recommend you do as you would when reading XML naturally.
In your code, try to find all the fields with the name attribute set to "name".
This process cannot be used to associate a name with an age. It is more natural to read the XML and check all resource elements. Then add to this element some information described in the field elements.
// Using LINQ to SQL
XDocument document = XDocument.Load("http://www.studiovincent.net/list.xml"); // Loads the XML document.
XElement resourcesElement = document.Root.Element("resources"); // Gets the "resources" element that is in the root "list" of the document.
XElement resourceElementVincent = (from resourceElement in resourcesElement.Elements("resource")// Gets all the "resource" elements in the "resources" element
let fieldNameElement = resourceElement.Elements("field").Single(fieldElement => fieldElement.Attribute("name").Value == "name") // Gets the field that contains the name (there one and only one "name" field in the "resource" element -> use of Single())
where fieldNameElement.Value == "Vincent" // To get only resources called "Vincent"
select resourceElement).Single(); // We suppose there is one and only 1 resource called "Vincent" -> Use of Single()
XElement fieldAgeElement = resourceElementVincent.Elements("field").Single(fieldElement => fieldElement.Attribute("name").Value == "age"); // Gets the corresponding "age" field
int age = int.Parse(fieldAgeElement.Value, CultureInfo.InvariantCulture); // Gets the age by Parse it as an integer
Console.WriteLine(age);
Does it do what you want?

Consider this below XML is there as one of the SQL table's column.
<Root>
<Name>Dinesh</Name>
<Id>2</Id>
</Root>
The objective of the query is to fetch the Name from the XML. In this example we will fetch the 'Dinesh' as the value.
var Query = (from t in dbContext.Employee.AsEnumerable()
where t.active == true
select new Employee
{
Id = t.AtpEventId,
Name = XDocument.Parse(t.Content).Descendants("Root").Descendants("Name").ToList().
Select(node => node.Value.ToString()).FirstOrDefault()
});
Note the following:
t.active == true is just an example to make some condition if needed.
Please note, in the above LINQ query, always use the AsEnumerable, as I did in the first line.
Descendants("Root").Descendants("Name") - here "Root" should be the element matching with the XML, and under Root we have Name element.

Related

How to read specific fields from XML and load into Oracle db

my XML :
- <resources start="0" count="188">-
- <resource classname="Quote">
<field name="name">USD/GEL</field>
<field name="price">2.418900</field>
<field name="symbol">GEL=X</field>
<field name="ts">1488758461</field>
<field name="type">currency</field>
<field name="utctime">2017-03-06T00:01:01+0000</field>
<field name="volume">0</field>
</resource>-
</resources>
C# Code:
var xmlNodes = xElement.Descendants("resource")
.Select(e => new
{
ConvertFrom = e.Attribute("symbol").Value,
ConvRate = e.Attribute("price").Value,
ConvDate = e.Attribute("utctime").Value
});
I tried the above code to fetch and load into oracle but i got a below error.
System.Linq.Enumerable+WhereSelectEnumerableIterator2[System.Xml.Linq.XElement,<>f__AnonymousType03[System.String,System.String,System.String]]
Please help me to resolve this issue.
I think you have misunderstood Attribute method, the name of the attribute is name, symbol is the value, so your query could be this way:
var xmlNodes = xElement.Descendants("resource")
.Select(e => new
{
ConvertFrom = (string)e.Elements().FistOrDefault(r=>r.Attribute("name").Value=="symbol"),
ConvRate = (string)e.Elements().FistOrDefault(r=>r.Attribute("name").Value=="price"),
ConvDate = (DateTime)e.Elements().FistOrDefault(r=>r.Attribute("name").Value=="utctime"),
});

Get value from XML code where attribute has particular value [using XElement]

I am attempting to retrieve values from certain nodes in an XML response by using XElement where the attribute value is "id=x".
This is what the XML response looks like.
<customfields>
<group id="6" title="Help Desk Ticket Categories" displayorder="1">
<field id="73" title="Second level classification" type="6" name="zscyz3a30h1q"><![CDATA[-- unassigned --]]></field>
</group>
<group id="9" title="For CS" displayorder="4">
<field id="82" title="CS Root Cause Classification " type="6" name="pye19ntzyp8v"><![CDATA[--Unassigned--]]></field>
<field id="84" title="Staff Responsible" type="6" name="7gy8bfu8tidv"><![CDATA[-- unassigned --]]></field>
<field id="93" title="Customer Package" type="6" name="fxk9rqtlw0fa"><![CDATA[--Unassigned--]]></field>
</group>
<group id="2" title="Client Info" displayorder="3">
<field id="5" title="Customer Name" type="1" name="77004d0323"><![CDATA[BigG]]></field>
<field id="17" title="Account Number" type="1" name="d1abccc1a0" /><![CDATA[123]]></field>
<field id="16" title="Contact Name" type="1" name="93d2b9adf1" /><![CDATA[george]]></field>
<field id="13" title="Phone No." type="1" name="0aa31be4b8" /><![CDATA[456]]></field>
</group>
</customfields>
This is the code I'm using now (which works), but I'd rather retrieve values for field with "id"="5" rather than have the value retrieved through a descendant index.
XElement root = XElement.Parse(GetTicketCustomFields(ticketID));
kCustomer = (string)(from el in root.Descendants("field") select el).ElementAt(4);
kAccountNumber = (string)(from el in root.Descendants("field") select el).ElementAt(5);
kName = (string)(from el in root.Descendants("field") select el).ElementAt(6);
kPhone = (string)(from el in root.Descendants("field") select el).ElementAt(7);
Thanks for
I would use XPath
var root = XDocument.Parse(xmlstring);
var accountNumber = root.XPathSelectElement("//field[#id='17']").Value;
or
var accountNumber = root.XPathSelectElement("//field[#title='Account Number']").Value;
Using Linq2Xml is also possible
var accountNumber = root.Descendants("field")
.FirstOrDefault(F => F.Attribute("id").Value == "17")
.Value;
Use XPath as #L.B. suggests.
If you're using Visual Studio there's a plugin written by yours truly which can help you find the XPath of a given element or attribute, to get you on your way: XPath Information

Data retrieving from XElemnt using LINQ

I have an XElement as follows
<row>
<field name="field1">Test1</field>
<field name="field2">Test2</field>
<field name="field3">Test3</field>
</row>
I want to retrieve value Test2 using the attribute value field2 using LINQ.I tried the following code
var data= item.Elements("field").Single(x => x.Attribute("name").Value == "field2");
It's not working.When I run the code it fails with error Sequence contains no matching element >
I don't know what I'm missing here.How can I retrieve the value using LINQ
I found the mistake. The code should be like this
var data = item.Elements().Single(x => x.Attribute("name").Value == "field2").Value;

Reading elements into a dictionary object using LINQ

I am using traditional XmlReader to parse a xml document into a dictionary? However i am in search for less complicated method minimum lines of code. I have the following Xml document
<Msg>
<field id="0" value="0100"/>
<field id="3" value="310000"/>
<field id="7" value="0101150110"/>
<field id="11" value="000002"/>
</Msg>
Is it possible to split the following xml document into a dictionary object with key being the attribute and value being the value of that element?
eg:-
Key = 0 value =0100
Rather than using XmlReader, I'd suggest using LINQ to XML, at which point it's really simple:
var dictionary = document.Descendants("field")
.ToDictionary(x => (int) x.Attribute("id"),
x => (string) x.Attribute("value"));
var query = (from element in document.Descendants("field"))
.ToDictionary(pair => (int)pair.Attribute("id"),
pair => (string)pair.Attribute("value"));

Filter document by element attributes using LINQ to XML

I have this XML document :
<?xml version="1.0" encoding="UTF-8"?>
<teryt>
<catalog name="TERC" type="all" date="2010-01-01">
<row>
<field name="Woj">1</field>
<field name="City">Warszawa</field>
<field name="Name">Mazowsze</field>
</row>
<row>
<field name="WojId">1</field>
<field name="City"/>
<field name="Name">Mazowsze</field>
</row>
<row>
<field name="Woj">2</field>
<field name="City"/>
<field name="Name">Slask</field>
</row>
</catalog>
</teryt>
And now I want to get only rows which don't have value in field with attribute City (using LINQ to XML).
Do you mean something like:
var rows = from row in doc.Root.Elements("rows")
where !row.Elements("field")
.Any(x => (string) x.Attribute("name") == "City"
&& x.Value != "")
select row;
That says, "find all rows which don't have any non-empty field elements with a name attribute of City". I think that's what you're after...
Something like:
var query = from row in xdoc.Descendants("row")
where row.Elements("field")
.Any(ff => ff.Attribute("name").Value == "City"
&& String.IsNullOrWhitespace(ff.Value))
select row;
This is predicated on the desire to find every row without a City value.
Once you have loaded your xml document into an XDocument object you can access its tags. So you should grab the Root element of your XDocument and navigate down to the row tags with the Elements method. And when you have all your tags in a collection you can sort out the ones with no city field. I'm almost sure that there is a HasValue property on the xml elements which tells you if it has value or not. But if there isn't one, you can check the Value property which would be empty or null.
So now a little code for this, the way I like:
XDocument doc = XDocument.Load("yourfile");
var tags = doc.Root.Element("catalog")
.Elements("row")
.Where(r=>r.Elements("field")
.Single(f=>f.Attribute("name").Value == "City"
&& string.IsNullOrWhitespace(f.Value)));
It translates into something like this: Take the document, select the root of the document, take the element named "catalog", and give me all the "row" elements, where it is true, that if the "row" has a "field" element with the "name" attribute set to "City", it is null, empty string, or whitespace.
Now this may not be so easy to understand if you are new to this, but this is the way I would do it. You may add a few null-checks but this is up to you now.

Categories