I'm just learning Linq, and stuck on what I hope is fairly simple. My xml document is like:
<?xml version="1.0" encoding="utf-8"?>
<XDOC>
...
<ItemsDetail>
<Item name="Item1">
<data1>
<Data type="classA">55</Data>
<Data type="classB">66</Data>
</data1>
<data2>
<Data type="classA">77</Data>
<Data type="classB">88</Data>
</data2>
</Item>
</ItemsDetail>
</XDOC>
So I load my XML above into an XDocument type and then query the
var query = from p in ILSXml.Elements("XDOC").Elements("ItemsDetail").Elements("Item")
select p;
Then I run a foreach on on the query.
foreach (var record in query)
{
Console.WriteLine("Name: {0}", record.Attribute("Name").Value);
Console.WriteLine("Data1 ClassA: {0}", record.Element("data1").Element("Data").Attribute("classA").Value);
}
So the line:
Console.WriteLine("Data1 ClassA: {0}", record.Element("data1").Element("Data").Attribute("classA").Value);
does not work which, is what I was pretty much expecting. Do I have to run another series of queries or run some inline anonymous methods?
Oh and please don't comment on the xml, it's not mine, I just have to work with it.
I assume that you're trying to get the value 55? You can use the First method to find the first "Data" element with a "type" attribute value of "classA".
record.Element("data1")
.Elements("Data")
.First(data => data.Attribute("type").Value == "classA")
.Value
Note that the above solution is quite fragile. Any change to the structure of the input xml document is likely to cause a null reference exception.
You can also query XML documents using the more compact XPath query language. XPath has the ability to filter elements using a simple expression wrapped in square brackets. Your code would then look something like this:
foreach (var record in ILSXml.XPathSelectElements("XDOC/ItemsDetail/Item"))
{
Console.WriteLine("Name: {0}",
record.Attribute("name").Value);
Console.WriteLine("Data1 ClassA: {0}",
record.XPathSelectElement("data1/Data[#type='classA']").Value);
}
Related
I'm working with a specific FundsXML-Schema trying to get all Assetss of a specific XML-File to iterate through.
Short example of xml-file:
<?xml version="1.0" encoding="utf-8"?>
<FundsXML xmlns="http://www.fundsxml.org/XMLSchema/3.0.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="3.0.5" xsi:schemaLocation="http://www.fundsxml.org/XMLSchema/3.0.5 FundsXML3.0.5.xsd">
<Date>2015-02-27</Date>
...
<AssetMasterData>
<Asset>
<SecurityCodes>
<ISIN>XXXXXXXXXXXX</ISIN>
</SecurityCodes>
</Asset>
...
<Asset>
</AssetMasterData>
</FundsXML>
I want to iterate through Assets in there. I tried:
XDocument xmlTree = XDocument.Load(xmlPath);
XElement root = xmlTree.Root;
foreach (XElement f in root.Descendants())
{
System.Windows.MessageBox.Show(f.Name.ToString() +" ; "+f.Value.ToString());
}
Output: {http://www.fundsxml.org/XMLSchema/3.0.5}Date ; 2015-02-27
The second part would be to read ISIN of each Asset node.
But I hadn't time to do this, because I'm failing at the first part.
EDIT:
Solution was to search for namespace+name:
foreach (XElement f in root.Descendants("{http://www.fundsxml.org/XMLSchema/3.0.5}Asset"))
Best solution in my opinion:
foreach (XElement f in root.Descendants(xmlTree.Root.GetDefaultNamespace()+"Asset"))
As your XML is in a namespace, you need to add the namespace information to the Descendants query.
You can see an example here
You can try to get the
roots.Descendants()
Without filtering and check the nodes that it returns to confirm this.
Based on the sample data you've provided
<Asset></Asset>
doesn't appear to have any data in it. You would need to get
foreach (XElement f in root.Descendants("ISIN"))
I think anyway. If there's no actual text then you will get a blank or empty value?? So it sounds like it's returning what you're asking for??
XML
<?xml version="1.0" encoding="utf-8" ?>
<animals>
<animal id="fisrt">
<type>Dog</type>
<name>Han</name>
</animal>
<animal id="second">
<type>Cat</type>
<name>Leia</name>
</animal>
</animals>
C#
using System.Xml.Linq;
string id = "second";
var filter = from ab in element.Elements("animal") where ab.Attribute("id").Equals(id) select ab;
foreach (XElement selector in filter)
{
label1.Content = selector.Element("name").Value;
}
What I need help with is selecting elements based on the parent element's id. The goal is to select the name who's parent's id is "second", so I'm trying to get "Leia". The problem I'm encountering is that nothing is happening to the label.
What am I doing wrong and how can I fix this issue. I'm also open to different approach if someone knows of a better way of achieving my goal.
You miss to check the value of attribute:
where ab.Attribute("id").Value.Equals(id)
Hope this help!
How about this:
string name = xdoc.Elements("animal")
.Where (e=>e.Attribute("id")=="first")
.Elements("name")
.Select(e=>e.Value)
.FirstOrDefault();
Essentially you want to put the condition about id attribute inside the where and continue the query.
I know this is the method annotation instead of linq syntax, I prefer it for being easier to read when things get hairy.
I've chosen the title here as my problem is I need to get the Item nodes mentioned in the example.
I have the following XML and am having problems using LINQ to query it, I've been able to parse XML before - however I've been stuck on this for hours and hope someone can help.
Here is my XML data below (example data):
<a:entry
xmlns:a="http://www.w3.org/2005/Atom">
<a:id>98765</a:id>
<info>Data Catalogue</info>
<data>
<items>
<item>
<id>123456</id>
<value>Item One</value>
</item>
<item>
<id>654321</id>
<value>Item Two</value>
</item>
</items>
</data>
<items>
<item>
<id>123456</id>
<value>Item One</value>
</item>
<item>
<id>654321</id>
<value>Item Two</value>
</item>
</items>
<a:author>
<a:name>Catalogue</a:name>
</a:author>
</a:entry>
I want to be able to extract the ID from the Item XML tag under Items, however there is an Items Tag with Item entries under data I DO NOT want these nodes at all - I want root/items/id/id if this were expressed as path. I've tried everything I know with LINQ so if someone could help, things to note although this is sample data it is based on the system - the format cannot be changed so that is not an acceptable solution.
I can't seem to determine where I'm going wrong - every LINQ expression I try returns nothing, I think the namespace is an issue and have tried to integrate this but I'm going in circles.
Solution must work in Silverlight and C#
I have tried the following:
IEnumerable<XElement> nodes =
element.Elements().Where(e => e.Name.LocalName == "items")
However this gets me all the "items" including the ones under "data" I don't want those.
If I do the following on my XML I do see the Names of the Elements displayed:
XElement element = XElement.Parse(data);
foreach (XElement node in element.Elements())
{
MessageBox.Show(node.Name.LocalName);
}
However when I do this I cannot see the node names under items at all - I've checked the XElement and it does have the node and when I output the names above it "items" shows up along with info and id!
foreach (XElement node in element.Elements("items"))
{
MessageBox.Show(node.Name.LocalName);
}
Assuming element is your <a:entry> element:
var ids = element.Element("items")
.Elements("item")
.Select(item => item.Element("id").Value);
The Element and Elements methods return only direct children, not all descendants, so it doesn't return the <items> element which is under <data>
I had a blank Namespace Declaration in my XML I hadn't noticed once I added this into my code it worked - forgot LINQ is very NameSpace oriented!
XNamespace ns = "http://example.org/namespace";
var ids = element.Element(ns + "items")
.Elements("item")
.Select(item => item.Element("id").Value);
Greeting,
What is the best practice to read all attributes from a child elements by ID attributes using C# in xml file listed down.
Thank you,
<?xml version="1.0" encoding="utf-8"?>
<WinDLN>
<Program ID="1" Name="CIS562" StartDate="9/8/2010 5:50:00 PM" EndDate="9/8/2010 9:15:00 PM" />
<Program ID="2" Name="CIS532" StartDate="10/8/2010 5:50:00 PM" EndDate="10/8/2010 9:15:00 PM" />
<Program ID="3" Name="ECE552" StartDate="6/8/2010 5:50:00 PM" EndDate="6/8/2010 9:15:00 PM" />
</WinDLN>
The following LINQ call should do the trick:
var attrs =
doc.Descendants("Program").First(prog =>
prog.Attribute("ID").Value == "2").Attributes();
The Descendants method gives you all elements (anywhere) in the XML document that are named "Program". Using First, you can get the first one that matches some specified predicate (e.g. has "ID" equal to "2"). Note that you can use FirstOrDefault if you want to get null when there is no such element. Finally, Attributes gives you a collection of all attribtues of the element.
I think that using LINQ to XML if you can is preferrable - you'll write the same code when working with XML or other data sources, so reading and writing the code is easy (once you learn LINQ).
There are many ways to do it, e.g. LINQ over XML. But using Xpath is definitely not dead yet:
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
string xml = #"... your xml ";
doc.LoadXml(xml);
// Using SelectNodes with Xpath
XmlNodeList list = doc.SelectNodes("WinDLN/Program[#ID='2']");
Console.WriteLine(list.Count); // prints 1
list = doc.SelectNodes("WinDLN/Program[#ID]");
Console.WriteLine(list.Count); // prints 3 (selected all IDs)
}
}
What method you'll choose is most often a matter of taste, select the API you're most comfortable with.
I have been trying to parse this xml in c#
<schema uri=http://blah.com/schema >
<itemGroups>
<itemGroup description="itemGroup1 label="itemGroup1">
<items>
<item description="The best" itemId="1" label="Nutella"/>
<item description="The worst" itemId="2" label="Vegemite"/>
</items>
</itemGroup>
</itemGroups>
</schema>
\itemGroup1\Nutella-The best
\itemGroup1\Vegemite-The worst
Any help or direction would be appreciated.
XDocument xDoc = XDocument.Load(myXml); //load your XML from file or stream
var rows = xDoc.Descendants("item").Select(x => string.Format(
#"\{0}-{1}\{2}-{3}",
x.Ancestors("itemGroup").First().Attribute("description").Value,
x.Ancestors("itemGroup").First().Attribute("label").Value,
x.Attribute("label").Value,
x.Attribute("description").Value));
Let's break down what we're doing:
xDoc.Descendants("item") gets us all <item> elements in the entire document
Select(x => string.Format(format, args) projects each <item> we got from the last operation into whatever format we specify in the lambda. In this case, a formatted string.
In terms of the XML tree, we're "sitting at" the <item> level, so we need to roll back up the tree to get the data for the parent group using Ancestors. Since that method returns a sequence of elements, we know we want the first (nearest to us) so we can read its attribute.
Now you have an IEnumerable<string>, one for each <item> in your XML document and the information in the format you specified:
foreach(string row in rows)
{
Console.WriteLine(row);
}