Select an element who as a last child with property - c#

<bus>
<port>
<req>
<item>
[...]
</item>
</req>
[...]
<req>
<item>
[...]
</item>
</req>
</port>
[...]
<port>
<req>
<item>
[...]
</item>
</req>
[...]
<req>
<item>
[...]
</item>
</req>
</port>
</bus>
<bus>
[...] (same as before)
</bus>
I have this structure; all the structures repeats themselves. I need to select the last port element of a bus which has a last child with property "mode"=="read".
It can exist a bus which has a last port element with a last child with property different from "read", so I need to choose the right port element.
I tried lots of tries, last one is this, but does not works:
var modbusportSelected = Elements("bus").Elements("port")
.Where( x => x.Elements("req")
.Any(y => y.Attribute("mode").Value.Contains("read")))
.Last();
Any help would be greatly appreciated; also, I'm totally new with LINQ to XML and I cannot find a single webpage where to get the exact meaning of "Any" and if there are other operators, and if so, what they are.

It may be significant that your XML snippet needs a top level element. If you wrap what you have above in an outer tag, then your code appears to work provided you trap null references from any port elements which don't have a mode attribute. eg.
using System;
using System.Linq;
using System.Xml.Linq;
namespace ConsoleApp1
{
class Program
{
public static string xml = #"<topLevel><bus>
<port isCorrectNode='no'>
<req>
<item>
</item>
</req>
<req mode='read'>
<item>
</item>
</req>
</port>
<port isCorrectNode='yes'>
<req mode='read'>
<item>
</item>
</req>
<req>
<item>
</item>
</req>
</port>
</bus>
<bus>
</bus>
</topLevel>";
static void Main(string[] args)
{
XElement root = XElement.Parse(xml);
var found = root.Elements("bus").Elements("port")
.Where(x => x.Elements("req").Any(y => y.Attribute("mode") != null && y.Attribute("mode").Value.Contains("read")))
.Last();
var isThisTheCorrectNode = found.Attribute("isCorrectNode").Value;
Console.WriteLine(isThisTheCorrectNode);
}
}
}
will write yes
Edit: I've noticed your code looks for the last port which has any child req whose mode is 'read'. but your question asked for the last such req. In that case:
var wanted = root.Elements("bus").Elements("port")
.Where(x => x.Elements("req").Any() && // make sure there is a req element
x.Elements("req").Last().Attribute("mode") != null && // and it has the attribute
x.Elements("req").Last().Attribute("mode").Value.Contains("read")) // and it has the right value
.Last();

Related

How can I select a specific XML node and fetch the values in its child nodes

I'm trying to select a specific node and fetch the values in it's childnodes. This would normally be pretty easy, but the complication is that the nodes have the same name. My xml looks something like this;
<Settings>
<Config>
</Config>
<Items>
<Item>
<ID>Hello</ID>
<Pth>Somevalue</Pth>
<Zvb>True</Zvb>
<Ico>True</Ico>
</Item>
<Item>
<ID>Stack</ID>
<Pth>Somevalue</Pth>
<Zvb>False</Zvb>
<Ico>True</Ico>
</Item>
<Item>
<ID>Overflow</ID>
<Pth>Somevalue</Pth>
<Zvb>False</Zvb>
<Ico>True</Ico>
</Item>
</Items>
</Settings>
Each <ID>'s innertext is always unique. I now want to select the <Item> ,where it's <ID>'s innertext is "Stack". (I need the other childnode-values as well, like Pth, Zvb and Ico. So everything under <Item> basically)
I did this is powershell, and it looks something like this;
$script:specificItem = $dgvItems.rows[$_.RowIndex].Cells[1].Value
$script:fetch = #($xml.SelectNodes('//Item')) | Select-Object * | Where { $_.ID -like $specificItem }
So far I've got this (I'm in a RowEnter event of a datagridview):
XmlDocument xml = new XmlDocument();
xml.Load(GlobalVars.configfile);
int rowindex = dgvItemlist.CurrentCell.RowIndex;
dgvItemlist.Rows[rowindex].Cells[2].Value.ToString(); //This will contain for example "Stack"
XmlNodeList Items = xml.SelectNodes("//Items/Item"); //probably other ways to start as well
... but from here I struggle with filtering or selecting the one I want. I know this is a fairly common question, but I can't find a good solution for this exact issue.
You could also use XDocument (Linq to XML):
string xml =#"<Settings>
<Config>
</Config>
<Items>
<Item>
<ID>Hello</ID>
<Pth>Somevalue</Pth>
<Zvb>True</Zvb>
<Ico>True</Ico>
</Item>
<Item>
<ID>Stack</ID>
<Pth>Somevalue</Pth>
<Zvb>False</Zvb>
<Ico>True</Ico>
</Item>
<Item>
<ID>Overflow</ID>
<Pth>Somevalue</Pth>
<Zvb>False</Zvb>
<Ico>True</Ico>
</Item>
</Items>
</Settings>";
XDocument xdoc = XDocument.Parse(xml);
XElement desired = xdoc.Descendants("Item").FirstOrDefault(x=>(string)x.Element("ID")=="Stack");
if(desired!=null)
{
string Pth = (string)desired.Element("Pth");
string Zvb = (string)desired.Element("Zvb");
string Ico = (string)desired.Element("Ico");
}
desired will be the wanted element.
Try to change the last line of your code into:
XmlNodeList Items = xml.SelectNodes("//Items/Item[ID='Stack']");
This should return:
<Item>
<ID>Stack</ID>
<Pth>Somevalue</Pth>
<Zvb>False</Zvb>
<Ico>True</Ico>
</Item>
Try the following. It will return the specific node you are looking for.
XmlNode itemNode = doc.SelectSingleNode("//ID[text()='Stack']").ParentNode;

Order frequent XML Data by group using LINQ

I have an XDocument with this data:
<item>
<name>Name 1</name>
<group>foo</group>
...
</item>
<item>
<name>Name 2</name>
<group>bar</group>
...
</item>
<item>
<name>Name 3</name>
<group>foo</group>
...
</item>
That means I have 2 items with group = foo and 1 item with group = bar. How can I order that data by the most frequent group? Result:
<item>
<name>Name 1</name>
<group>foo</group>
...
</item>
<item>
<name>Name 3</name>
<group>foo</group>
...
</item>
<item>
<name>Name 2</name>
<group>bar</group>
...
</item>
Data is loaded like this:
XDocument xml = XDocument.Load(#"\path\data.xml");
You can use a simple GroupBy and OrderByDescending:
var items = xml.Root.Elements()
.GroupBy(r => r.Element("group").Value)
.OrderByDescending(r => r.Count())
.ToList();
Then simply remove all nodes and add them ordered:
xml.Root.RemoveAll();
xml.Root.Add(items);
If you want to work with objects instead of the xml, you'll first need to deserialize the xml into a List<Item>, where each Item is a class of the same structure in the xml.
After that, when you have the list you can use GroupBy:
var newList = list.GroupBy(i => i.Group) //group together by "group" value
.OrderByDescending(i => i.Count()) //simple ordering
.SelectMany(i => i) //flatten the hierarchy
.ToList(); //back to list

LINQ complex delete and search query

//assume that I have the following XML file.
<warehouse>
<cat id="computer">
<item>
<SN>1</SN>
<name>Toshiba</name>
<quantity>12</quantity>
<description>CPU: CORE I5 RAM: 3 GB HD: 512 GB</description>
<price>400 USD</price>
</item>
<item>
<SN>22</SN>
<name>Toshiba</name>
<quantity>12</quantity>
<description>CPU: CORE I5 RAM: 3 GB HD: 512 GB</description>
<price>400 USD</price>
</item>
</cat>
<cat id="Stationery">
<item>
<SN> 33 </SN>
<name>note books</name>
<quantity>250</quantity>
<description>Caterpiller</description>
<price>5 USD</price>
</item>
</cat>
<cat id="Furniture">
<item>
<SN> 1 </SN>
<name>dasd</name>
<quantity>asdasd</quantity>
<description>das</description>
<price>dasd</price>
</item>
<item>
<SN>44</SN>
<name>Toshiba</name>
<quantity>12</quantity>
<description>CPU: CORE I5 RAM: 3 GB HD: 512 GB</description>
<price>400 USD</price>
</item>
<item>
</cat>
</warehouse>
question 1 : I want to Delete <item> element and its child's using linq , where <cat id="computer"> and <SN> has a specific value like 44 .
question 2 : I want to make a query using TextBox and Literal1 which return a specic <item> and its child's . this query should be in linq.
for example
XDocument xmlDoc = XDocument.Load(Server.MapPath("/XML/Cat1.xml"));
var persons = from person in xmlDoc.Descendants("item")
where person.Element("SN").Value.Equals(DropDownList1.Text)
select person;
persons.Remove();
foreach (XElement person in persons.ToList())
{
person.Remove();
}
Try this:-
xmlDoc.Root.Descendants("cat").Where(x => x.Attribute("id").Value == "computer")
.Descendants("item").Where(x => x.Element("SN").Value.Trim() == Dropdownlist.Text)
.Remove();
xmlDoc.Save(#"YourXML.xml");
And for filtering you can replace the values at specific places you like. Also, I have used Trim directly, better check for empty strings first in your actual code.
Question 2:-
var result = xmlDoc.Descendants("item")
.Where(x => x.Element("SN").Value.Trim() == Dropdownlist.Text);
Regarding question one i would do something like this using method syntax:
doc.Descendants("cat")
.Where(x => String.Equals((string)x.Attribute("id"), "computer", StringComparison.OrdinalIgnoreCase))
.Elements("item")
.Where(x => (string)x.Element("SN") == "44")
.Remove();
Basically select all your cat elements and filter by attribute id = computer. Then select all items in each of those and filter through SN = 44.

How to correctly perform Linq-to-XML query?

I have a XDocument called currentIndex like that:
<INDEX>
<SUBINDEX>
<!-- Many tag and infos -->
<SUBINDEX>
<ITEM>
<IDITEM>1</IDITEM>
<ITEM>
<ITEM>
<IDITEM>2</IDITEM>
<ITEM>
...
<ITEM>
<IDITEM>n</IDITEM>
<ITEM>
</INDEX>
I would recreate a new XDocument similar to above one:
<INDEX>
<SUBINDEX>
<!-- Many tag and infos -->
<SUBINDEX>
<ITEM>
<IDITEM>2</IDITEM>
<ITEM>
</INDEX>
I want to do this in C#, I have tried starting in this way:
public void ParseItems(XDocument items)
{
IEnumerable<XElement> items = from a in indexGenerale.Descendants(XName.Get("ITEM"))
// where a.Element("IDITEM").Equals("2")
select a;
foreach(var item in items) {
// do something
}
}
Now the problem: If where clause is commented, items contains n elements (one for each ITEM tag), but if I remove that comments items is empty. Why this behaviour. How I need to perform a search?
Use an explicit cast:
from a in indexGenerale.Descendants("ITEM")
where (string)a.Element("IDITEM") == "2"
a.Element("IDITEM") will return an XElement and it will never be equal to "2".Maybe you meant a.Element("IDITEM").Value.Equals("2"), that will also work but explicit cast is safer.It doesn't throw exception if the element wasn't found`,

Need a Nested LINQ to XML query help

i have a XML file as follows:
<?xml version="1.0" encoding="utf-8" ?>
<publisher>
<name>abc</name>
<link>http://</link>
<description>xyz</description>
<category title="Top">
<item>
<title>abc</title>
<link>http://</link>
<pubDate>1</pubDate>
<description>abc</description>
</item>
<item>
<title>abc</title>
<link>http://</link>
<pubDate>2</pubDate>
<description>abc</description>
</item>
</category>
<category title="Top2">
<item>
<title>abc</title>
<link>http://</link>
<pubDate>1</pubDate>
<description>abc</description>
</item>
<item>
<title>abc</title>
<link>http://</link>
<pubDate>2</pubDate>
<description>abc</description>
</item>
</category>
</publisher>
I need to write a LINQ to XML query in C# which returns everything under a "category" tag based on the value of attribute provided. I have tried the following code but it gives me error. Any help will be appreciated:
System.Xml.Linq.XElement xml = System.Xml.Linq.XElement.Parse(e.Result);
IEnumerable<string> items = from category in xml.Elements("category")
where category.Attribute("title").Value == "Top"
select category.ToString();
IEnumerable<string> items = from category in xml.Descendants("category")
where category.Attribute("title").Value == "Top"
select category.ToString();
Of course, that's going to give you a list with one string in it. If you want just the string in it:
var items = (from category in xml.Descendants("category")
where category.Attribute("title").Value == "Top"
select category.ToString()).First();
But, if you want to continue processing the XML, you probably really want it as a XElement object:
var items = (from category in xml.Descendants("category")
where category.Attribute("title").Value == "Top"
select category).First();

Categories

Resources