How to get through attributes in xml via LINQ

Please help me with the script below that has xml and I want the code in C # LINQ

<?xml version="1.0" encoding="utf-8" ?> <root> <Countries> <Country name="India"> <state id="1"> Tamilnadu</state> <state> Karnataka</state> </Country> <Country name="America"> <state id="1"> WI</state> <state> AW </state> </Country> <Country name="Africa"> <state id="1"> Melbourne</state> <state> sydney </state> </Country> </Countries> </root> 

How to get state with id = 1 attribute via LINQ, so how can I extract name = attribute "India"? And how to give id = 1 I mean a numeric value without "1"

+4
source share
4 answers

If you use C# , you can do something like:

  XDocument document = XDocument.Load("filePath"); var states = (from state in document.Root.Descendants("state") where state.Attribute("id") != null && state.Attribute("id").Value == "1" select state).ToList(); 
+2
source

You can do the following:

Zero checking is important because judging by your structure without this null checking, you will get a NullReferenceException .

 XDocument xml = XDocument.Load("yourFileLocation"); var items = document.Root.Descendants("state") .Where(s => s.Attribute("id") != null && s.Attribute("id").Value == "1") .ToList(); 
+2
source

Try the following.

 XDocument xml = XDocument.Load(file); XElement state = xml.Root.Descendants("Country") .First(c => c.Attribute("name").Value == "India") .Descendants("state") .First(s => (int)s.Attribute("id") == 1); 

Next time publish what you tried first so that we can help you with your code.

I also did this without null checks. If no values ​​are found, it will die on First() . Your own security checks are up to you.

+2
source

I find the existing answers too detailed and lengthy. Imagine what happens if you intend to make a selection based on multiple attributes?

The most compact and expressive solution at the same time is to use XPath extensions (from the System.Xml.XPath namespace).

For example, to get the state with id = 1 in India:

 var xdoc = XDocument.Load(file); foreach (var element in xdoc.XPathSelectElements("//Country[@name='India']/state[@id=1]")) { Console.WriteLine("State " + element.Value + ", id " + (int)element.Attribute("id")); } 

To get all conditions in all countries that have any identifier:

 foreach (var element in xdoc.XPathSelectElements("//state[@id]")) { Console.WriteLine("State " + element.Value + ", id " + (int)element.Attribute("id")); } 

Etc.

You can find the XPath specification here .

0
source

Source: https://habr.com/ru/post/1499426/


All Articles