Python's xml.etree getiterator equivalent to C# - c#

I have this XML file : http://dl.dropbox.com/u/10773282/2011/perf.xml
It has two Class elements as is marked. I need to get two nodes with C#.
With Python, I can easily get them with etree.ElementTree as follows.
from xml.etree import ElementTree as et
from xml.etree.ElementTree import Element
tree = et.parse("perf.xml")
tss = tree.getiterator('Class')
for elem in tss:
tss_name = elem.find('ClassKeyName')
print tss_name.text
>> helloclass.exe
>> helloclass.exeFpga::TestMe
How can I do the same thing with C#?
SOLVED
using System;
using System.Xml;
using System.Xml.Linq;
using System.Linq;
namespace HIR {
class Dummy {
static void Main(String[] argv) {
XDocument doc = XDocument.Load("perf.xml");
var res = from p in doc.Root.Elements("Module").Elements("NamespaceTable").Elements("Class").Elements("ClassKeyName") select p.Value;
foreach (var val in res) {
Console.WriteLine(val.ToString());
}
}
}
}
>> helloclass.exe
>> helloclass.exeFpga::TestMe
Or
foreach (var elem in elems) {
var res = elem.Elements("ClassKeyName").ToList();
Console.WriteLine(res[0].Value);
}

You should try Linq to XML... Quite easy to use:
var xml = XDocument.Load(filename);
var res = from p in xml.Root.Elements("Class").Elements("ClassKeyName") select p.Value;

Try:
using System.Xml;
// ...
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
var matches = xmlDoc.SelectNodes("//Class/ClassKeyName");

Related

Filter Attributes in Xml in c# AND modify the Xml

I am trying to convert and Xml A into Xml B using C#.
XML A
<root>
<country>
<city name="Boston" value="100">
<city name="Boston" value="200">
</country>
</root>
XMl B(Expected)
<root>
<country>
<city name="Boston" value="300">
</country>
</root>
C# code:
var doc = XDocument.Load(path);
var myDocument = new XmlDocument();
myDocument.Load(path);
var nodes = myDocument.GetElementsByTagName("city");
var resultNodes = new List<XmlNode>();
foreach (XmlNode node in nodes)
{
if (node.Attributes != null && node.Attributes["name"] != null && node.Attributes["name"].Value == "Boston")
resultNodes.Add(node);
foreach(var elements in resultNodes)
{
elements.Attributes.RemoveNamedItem("Boston");
}
}
Basically what i wanted to do here is add the 2 values(100 &200)from 2 different Boston attributes from XML A and print into a new XML B file but lost a bit here as what goes into this block.
foreach (XmlNode i in resultNodes)
{
}
Problems like this is easy to create new XElements. See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<XElement> countries = doc.Descendants("country").ToList();
foreach (XElement oldCountry in countries)
{
XElement newCountry = new XElement("country");
var cities = oldCountry.Elements("city").GroupBy(x => (string)x.Attribute("name"));
foreach (var city in cities)
{
newCountry.Add(new XElement("city", new object[] { new XAttribute("name", city.Key), new XAttribute("value", city.Sum(x => (int)x.Attribute("value"))) }));
}
oldCountry.ReplaceWith(newCountry);
}
}
}
}

Replace the value by relying on the existing value in XML file

This is a sample XML file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Automation Test</string>
<string name="current_data_state_incoming_call">Incoming Call</string>
<string name="current_data_state_outgoing_call">Outgoing Call</string>
<string name="current_data_state_missed_call">Missed Call</string>
<string name="current_data_state_photo">Photo</string>
<string name="current_data_state_video">Video</string>
<string name="current_data_state_mp3">MP3</string>
<string name="current_data_state_voice_memo">Voice Memo</string>
<string name="current_data_state_phone_book">Phone Book</string>
<string name="current_data_state_phone_booksim">Phone Book(SIM)</string>
<string name="current_data_state_etc">Etc</string>
<string name="current_data_state_schedule">S Planner</string>
</resources>
I have a large file XML file and I want to replace the values in elements depending on their original value.
For example, I want to replace "Outgoing Call" with another word.
I tried this code:
XmlDocument xdoc = new XmlDocument();
xdoc.Load("strings.xml");
XmlElement root = xdoc.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName("string");
for (int i = 0; i < elemList.Count; i++)
{
xdoc.Save("strings.xml");
if (elemList[i].InnerText == "Incoming Call")
{
// xdoc.LoadXml(File.ReadAllText("strings.xml").Replace(elemList[i].InnerText, "صندوق"));
// MessageBox.Show(elemList[i].InnerText);
elemList[i].SelectSingleNode("resources/string").InnerText="مكالمات قادمة";
xdoc.Save("strings.xml");
}
}
and this code
XmlDocument xdoc = new XmlDocument();
xdoc.Load("strings.xml");
XmlNodeList aNodes = xdoc.SelectNodes("resources/string");
foreach (XmlNode node in aNodes)
{
XmlNode child1 = node.SelectSingleNode("string");
if(child1.InnerText == "Incoming Call")
{
child1.InnerText = "اتصالات قادمة";
}
}
xdoc.Save("strings.xml");
I can not replace the value.
===================================
thanx i solve my prob
var root2 = new XmlDocument();
root2.Load("strings.xml");
var root = new XmlDocument();
root.Load("strings2.xml");
foreach (XmlNode e1 in root2.GetElementsByTagName("string"))
{
string a = e1.Attributes["name"].Value;
foreach (XmlNode ee in root.GetElementsByTagName("string"))
{
string b = ee.Attributes["name"].Value;
if (a == b)
{
e1.FirstChild.Value = ee.FirstChild.Value;
}
}
}
root.Save("strings.xml");
I would use LINQ to XML for this. It makes all kinds of things much simpler than XmlDocument. Here's a complete example to perform a replacement (loading input.xml and writing output.xml):
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument doc = XDocument.Load("input.xml");
ReplaceValue(doc, "Outgoing Call", "Other value");
doc.Save("output.xml");
}
static void ReplaceValue(XDocument doc, string original, string replacement)
{
foreach (var element in doc.Descendants("string").Where(x => x.Value == original))
{
element.Value = replacement;
}
}
}
You could easily change the method to throw an exception if it didn't find the value you were trying to replace, or if it found more than one element.
An alternative to replacing by value would be to replace by the name attribute, which would be a trivial change:
static void ReplaceNamedValue(XDocument doc, string name, string replacement)
{
foreach (var element in doc.Descendants("string")
.Where(x => (string) x.Attribute("name") == name))
{
element.Value = replacement;
}
}
You'd then call it like this:
ReplaceNamedValue(doc, "current_data_state_outgoing_call", "Other value");
You may want to create file on xml on the fly instead of replace. I prefer using the newer Net library xml linq (XDocument) rather than the older version XmlDocument. Here is an example of the code I would use :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string ident = "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources></resources>";
XDocument doc = XDocument.Parse(ident);
XElement resources = doc.Root;
resources.Add(new XElement("string", new object[] {
new XAttribute("name","app_name"),
"Automation Test"
}));
resources.Add(new XElement("string", new object[] {
new XAttribute("name","current_data_state_incoming_call"),
"مكالمات قادمة"
}));
}
}
}
Here is code for replacement
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement resource = doc.Root;
Dictionary<string, XElement> dict = resource.Elements()
.GroupBy(x => (string)x.Attribute("name"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
if(dict.ContainsKey("app_name"))
{
dict["app_name"].SetValue("Automation Test");
}
if (dict.ContainsKey("current_data_state_incoming_call"))
{
dict["current_data_state_incoming_call"].SetValue("مكالمات قادمة");
}
}
}
}

how do you retrieve xml data from nested nodes

<CustomerOrders>
<Customers>
<CustomerID>ALFKI</CustomerID>
<Orders>
<OrderID>10643</OrderID>
<CustomerID>ALFKI</CustomerID>
<OrderDate>1997-08-25</OrderDate>
</Orders>
<Orders>
<OrderID>10692</OrderID>
<CustomerID>ALFKI</CustomerID>
<OrderDate>1997-10-03</OrderDate>
</Orders>
<CompanyName>Alfreds Futterkiste</CompanyName>
</Customers>
<Customers>
<CustomerID>ANATR</CustomerID>
<Orders>
<OrderID>10308</OrderID>
<CustomerID>ANATR</CustomerID>
<OrderDate>1996-09-18</OrderDate>
</Orders>
<CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
</Customers>
</CustomerOrders>
How do you retrieve OrderID,CustomerID and OrderDate? i have been trying it for hours already. Can someone help me? Thanks!
XmlNodeList xmlnode = doc.GetElementsByTagName("Customers");
HtmlGenericControl div = new HtmlGenericControl("div");
for(int i = 0; i < xmlnode.Count; i++)
{
Label lbl2 = new Label();
lbl2.Text = xmlnode[i].ChildNodes[1].Name;
div.Controls.Add(lbl2);
RadioButtonList rb1 = new RadioButtonList();
rb1.Items.Add(xmlnode[i].ChildNodes[1].InnerText+"<br>");
div.Controls.Add(rb1);
}
div1.Controls.Add(div);
You can use the XDocument class and its decendants. You can use XPath expressions to delve deeper into the code:
e.g.
using System.Xml.Linq
using System.Xml.XPath
....
XDocument doc= XDocument.Load("sample.xml");
XElement root= doc.Element("CustomerOrders");
var result= root.XPathSelectElements("Customers/CustomerId");
foreach(var customerid in result)
{
.....
}
Depending on what you want to achieve this should put you at the right track. While I was typing the answer, another answer proposes to use XmlDocument class. That should work as well, but when using XDocument you can use Linq, which adds a lot of flexibilty.
XmlDocument doc = new XmlDocument();
doc.LoadXml("yourxmldata");
XmlNodeList customers = doc.DocumentElement.SelectNodes("Customers");
foreach (XmlNode customer in customers)
{
XmlNodeList customerOrders = customer.SelectNodes("Orders");
string customername = customer["CustomerID"].InnerText;
foreach (XmlNode customerOrder in customerOrders)
{
string orderid = customerOrder["OrderID"].InnerText;
string orderdate = customerOrder["OrderDate"].InnerText;
}
}
Here is everything using Xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication47
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants("Customers").Select(x => new
{
customerID = (string)x.Element("CustomerID"),
companyName = (string)x.Element("CompanyName"),
orders = x.Elements("Orders").Select(y => new {
orderID = (int)y.Element("OrderID"),
customerID = (string)y.Element("CustomerID"),
date = (DateTime)y.Element("OrderDate")
}).ToList()
}).ToList();
}
}
}

Extracting values from serialized XML in C#

I have the following serialized XML :
<DataItem type="System.PropertyBagData" time="2017-02-03T09:50:29.1118296Z" sourceHealthServiceId="">
<Property Name="LoggingComputer" VariantType="8">g2aaS03OsX/9e5SSikdrVjFb4tkwhVUWeGh6pOv8nJ0=</Property>
<Property Name="EventDisplayNumber" VariantType="8">4502</Property>
<Property Name="ManagementGroupName" VariantType="8">/FTyfF2bs7hBhlQMJfSABYkkuTU98A80WiXu9TlL98w=</Property>
<Property Name="RuleName" VariantType="8">CollectNetMonInformation</Property>
<Property Name="ModuleTypeName" VariantType="8"/>
<Property Name="StackTrace" VariantType="8">System.Exception: [2/3/2017 9:50:29 AM][InitializeDataReceiver], CreateFile Error : 2 WaitNamedPipe Error : 2 Pipe guid is : d0c4c51e-543b-4f25-8453-40000066967d</Property>
</DataItem>
To extract the values of "Property" tags, i have written the following c# code:
using System.IO;
using System;
using System.Xml;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
string s = "<DataItem type=\"System.PropertyBagData\" time=\"2017-02-03T09:50:29.1118296Z\" sourceHealthServiceId=\"\"><Property Name=\"LoggingComputer\" VariantType=\"8\">g2aaS03OsX/9e5SSikdrVjFb4tkwhVUWeGh6pOv8nJ0=</Property><Property Name=\"EventDisplayNumber\" VariantType=\"8\">4502</Property><Property Name=\"ManagementGroupName\" VariantType=\"8\">/=</Property><Property Name=\"RuleName\" VariantType=\"8\">CollectNetMonInformation</Property><Property Name=\"ModuleTypeName\" VariantType=\"8\"></Property><Property Name=\"StackTrace\" VariantType=\"8\">System.Exception: [2/3/2017 9:50:29 AM][InitializeDataReceiver]: 2 WaitNamedPipe Error : 2 Pipe guid is : </Property></DataItem>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(s);
XmlNodeList xnList = xml.SelectNodes("/DataItem");
foreach (XmlNode xn in xnList)
{
string firstName = xn["Property"].InnerText;
Console.WriteLine(firstName);
}
}
}
when i run the program, i get the output as "g2aaS03OsX/9e5SSikdrVjFb4tkwhVUWeGh6pOv8nJ0=" which is the value of first Property tag but no other value. How to fix this.
Thanks in advance.
Try this
string s = "<DataItem type=\"System.PropertyBagData\" time=\"2017-02-03T09:50:29.1118296Z\" sourceHealthServiceId=\"\"><Property Name=\"LoggingComputer\" VariantType=\"8\">g2aaS03OsX/9e5SSikdrVjFb4tkwhVUWeGh6pOv8nJ0=</Property><Property Name=\"EventDisplayNumber\" VariantType=\"8\">4502</Property><Property Name=\"ManagementGroupName\" VariantType=\"8\">/=</Property><Property Name=\"RuleName\" VariantType=\"8\">CollectNetMonInformation</Property><Property Name=\"ModuleTypeName\" VariantType=\"8\"></Property><Property Name=\"StackTrace\" VariantType=\"8\">System.Exception: [2/3/2017 9:50:29 AM][InitializeDataReceiver]: 2 WaitNamedPipe Error : 2 Pipe guid is : </Property></DataItem>";
XDocument doc = XDocument.Parse(s);
var NodeNames = doc.Descendants("DataItem").Elements();
foreach (var item in NodeNames)
{
string firstName = item.Value;
Console.WriteLine(firstName);
}
XDocument is newer than XmlDocument. More readable and you can use LINQ.
var xElements = XDocument.Parse(yourXml).Descendants("Property");
xElements.ToList().ForEach(x=> Console.WriteLine(x.Value));
You can use Linq to XML :
var results = from node in XDocument.Parse(s).Descendants()
where node.Name == "Property"
select node.Value;
Result :
try this code:
using System.IO;
using System;
using System.Xml;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
string s = "<DataItem type=\"System.PropertyBagData\" time=\"2017-02-03T09:50:29.1118296Z\" sourceHealthServiceId=\"64ced8f3-385a-238c-eea4-008bab8ba249\"><Property Name=\"LoggingComputer\" VariantType=\"8\">g2aaS03OsX/9e5SSikdrVjFb4tkwhVUWeGh6pOv8nJ0=</Property><Property Name=\"EventDisplayNumber\" VariantType=\"8\">4502</Property><Property Name=\"ManagementGroupName\" VariantType=\"8\">/FTyfF2bs7hBhlQMJfSABYkkuTU98A80WiXu9TlL98w=</Property><Property Name=\"RuleName\" VariantType=\"8\">CollectNetMonInformation</Property><Property Name=\"ModuleTypeName\" VariantType=\"8\">Microsoft.EnterpriseManagement.Mom.Modules.NetmonDataSource.NetmonDataSource</Property><Property Name=\"StackTrace\" VariantType=\"8\">System.Exception: [2/3/2017 9:50:29 AM][InitializeDataReceiver]Exception while trying to connect to the agent :Could not open pipe, CreateFile Error : 2 WaitNamedPipe Error : 2 Pipe guid is : d0c4c51e-543b-4f25-8453-40000066967d</Property></DataItem>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(s);
XmlNodeList xnList = xml.SelectNodes("/DataItem/Property");
foreach (XmlNode xn in xnList)
{
string firstName = xn.InnerText;
Console.WriteLine(firstName);
}
}
}
Try this code:
Console.WriteLine("Hello, World!");
string s = "<DataItem type=\"System.PropertyBagData\" time=\"2017-02-03T09:50:29.1118296Z\" sourceHealthServiceId=\"\"><Property Name=\"LoggingComputer\" VariantType=\"8\">g2aaS03OsX/9e5SSikdrVjFb4tkwhVUWeGh6pOv8nJ0=</Property><Property Name=\"EventDisplayNumber\" VariantType=\"8\">4502</Property><Property Name=\"ManagementGroupName\" VariantType=\"8\">/=</Property><Property Name=\"RuleName\" VariantType=\"8\">CollectNetMonInformation</Property><Property Name=\"ModuleTypeName\" VariantType=\"8\"></Property><Property Name=\"StackTrace\" VariantType=\"8\">System.Exception: [2/3/2017 9:50:29 AM][InitializeDataReceiver]: 2 WaitNamedPipe Error : 2 Pipe guid is : </Property></DataItem>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(s);
XmlNodeList xnList = xml.SelectNodes("/DataItem");
foreach (XmlNode xn in xnList)
{
XmlNodeList propsList = xn.SelectNodes("Property");
foreach (XmlNode node in propsList)
{
string firstName = node.InnerText;
Console.WriteLine(firstName);
}
}
I like using a dictionary in cases like this using xml linq to create the dictionary :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, string> dict = doc.Descendants("Property")
.GroupBy(x => (string)x.Attribute("Name"), y => (string)y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}

How to Read XML tag values in C# [duplicate]

I am using this XML file:
<root>
<level1 name="A">
<level2 name="A1" />
<level2 name="A2" />
</level1>
<level1 name="B">
<level2 name="B1" />
<level2 name="B2" />
</level1>
<level1 name="C" />
</root>
Could someone give me a C# code using LINQ, the simplest way to print this result:
(Note the extra space if it is a level2 node)
A
A1
A2
B
B1
B2
C
Currently I have written this code:
XDocument xdoc = XDocument.Load("data.xml"));
var lv1s = from lv1 in xdoc.Descendants("level1")
select lv1.Attribute("name").Value;
foreach (var lv1 in lv1s)
{
result.AppendLine(lv1);
var lv2s = from lv2 in xdoc...???
}
Try this.
using System.Xml.Linq;
void Main()
{
StringBuilder result = new StringBuilder();
//Load xml
XDocument xdoc = XDocument.Load("data.xml");
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new {
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
//Loop through results
foreach (var lv1 in lv1s){
result.AppendLine(lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result);
}
Or, if you want a more general approach - i.e. for nesting up to "levelN":
void Main()
{
XElement rootElement = XElement.Load(#"c:\events\test.xml");
Console.WriteLine(GetOutline(0, rootElement));
}
private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
A couple of plain old foreach loops provides a clean solution:
foreach (XElement level1Element in XElement.Load("data.xml").Elements("level1"))
{
result.AppendLine(level1Element.Attribute("name").Value);
foreach (XElement level2Element in level1Element.Elements("level2"))
{
result.AppendLine(" " + level2Element.Attribute("name").Value);
}
}
Here are a couple of complete working examples that build on the #bendewey & #dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:
//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ1
{
static void Main( )
{
//Load xml
XDocument xdoc = XDocument.Load(#"c:\\data.xml"); //you'll have to edit your path
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new
{
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
StringBuilder result = new StringBuilder(); //had to add this to make the result work
//Loop through results
foreach (var lv1 in lv1s)
{
result.AppendLine(" " + lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result.ToString()); //added this so you could see the output on the console
}
}
And next:
//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ
{
static void Main( )
{
XElement rootElement = XElement.Load(#"c:\\data.xml"); //you'll have to edit your path
Console.WriteLine(GetOutline(0, rootElement));
}
static private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
}
These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.
EDIT: added #eglasius' example as well since it became useful to me:
//#eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ2
{
static void Main( )
{
StringBuilder result = new StringBuilder(); //needed for result below
XDocument xdoc = XDocument.Load(#"c:\\deg\\data.xml"); //you'll have to edit your path
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Console.WriteLine(result);//added this so you could see the result
}
}
XDocument xdoc = XDocument.Load("data.xml");
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Ps. You have to use .Root on any of these versions.
Asynchronous loading of the XML file can improve performance, especially if the file is large or if it takes a long time to load. In this example, we use the XDocument.LoadAsync method to load and parse the XML file asynchronously, which can help to prevent the application from becoming unresponsive while the file is being loaded.
Demo: https://dotnetfiddle.net/PGFE7c (using XML string parsing)
Implementation:
XDocument doc;
// Open the XML file using File.OpenRead and pass the stream to
// XDocument.LoadAsync to load and parse the XML asynchronously
using (var stream = File.OpenRead("data.xml"))
{
doc = await XDocument.LoadAsync(stream, LoadOptions.None, CancellationToken.None);
}
// Select the level1 elements from the document and create an anonymous object for each element
// with a Name property containing the value of the "name" attribute and a Children property
// containing a collection of the names of the level2 elements
var results = doc.Descendants("level1")
.Select(level1 => new
{
Name = level1.Attribute("name").Value,
Children = level1.Descendants("level2")
.Select(level2 => level2.Attribute("name").Value)
});
foreach (var result in results)
{
Console.WriteLine(result.Name);
foreach (var child in result.Children)
Console.WriteLine(" " + child);
}
Result:
A
  A1
  A2
B
  B1
  B2
C

Categories

Resources