Reading Complex XML Attributes

I have an XML file that uses a combination of attributes and tags in which there is data.

I have no control over the structure of the XML file, but I'm currently switching gears to see LINQ to parse this and wonder if there are any opinions on how best to approach this structure:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE call_flow SYSTEM "../../../../dtds/Callflow_1-1.dtd"> <call_flow version="1.1" serial="13903" first_element="Element1"> <element_def name="Element1"> <voice class="com.classname.Name"> <static>Element1.xml</static> </voice> <exit_state name="done"> <next_element>Element2</next_element> </exit_state> </element_def> <element_def name="Element2"> <voice class="com.classname.Name2"> <static>Element2.xml</static> </voice> <exit_state name="option1"> <next_element>Element3</next_element> </exit_state> <exit_state name="option2"> <next_element>Element4</next_element> </exit_state> </element_def> <element_def name="Element3"> <voice class="com.classname.Name3"> <static>Element3.xml</static> </voice> <exit_state name="done"> <next_element>Element4</next_element> </exit_state> </element_def> <element_def name="Element4"> <decision> <class src="com.classname.Name4"/> </decision> <exit_state name="0"> <next_element>Element3</next_element> </exit_state> <exit_state name="1"> <next_element>Element5</next_element> </exit_state> </element_def> <element_def name="Element5"> <voice class="com.classname.Name5"> <static>element5.xml</static> </voice> </element_def> </call_flow> 

I can find many examples of LINQ code, but I don’t see how I would get both values ​​for Next_Element and the property name_def "name".

If someone can help and maybe point me in the right direction, I would appreciate it.

+4
source share
2 answers

How about this:

 var doc = XDocument.Load("myXml.xml"); var list = doc.Descendants("element_def") .Select(x => new { elDefName = x.Attribute("name").Value, nextEl = x.Descendants("next_element").Select(y=> y.Value).ToList() }); 

It will return IEnumerable anonymous objects, where elDefName will be the value of the attribute name element_def node and nextEl will contain a list of possible next_element .

0
source
 XDocument xdoc = XDocument.Load(path_to_xml); var query = from ed in xdoc.Descendants("element_def") select new { Name = (string)ed.Attribute("name"), NextElements = ed.Elements("exit_state") .Select(es => (string)es.Element("next_element")) }; 

This query returns a sequence of anonymous objects that will have a Name property containing the element_def name, and the names of the following elements as IEnumerable<string> .

+3
source

All Articles