linq question

  • Thread starter Thread starter CSharper
  • Start date Start date
C

CSharper

I have an xml file the following

<?xml version="1.0" encoding="utf-8" ?>
<Source Met="Source">
<Name SourceName="0001">
<Location>Texas</Location>
<Values>
<Value id="1" Amount="1.0" />
<Value id="2" Amount="2.0" />
</Values>
</Name>
<Name SourceName="0002">
<Location>Texas</Location>
<Values>
<Value id="10" Amount="1.0" />
<Value id="20" Amount="2.0" />
</Values>
</Name>
</Source>

I want to convert this XML into a normalised string and I would like
the string result to be
"Source", "0001", "Texas", "1", "1.0"
"Source", "0001", "Texas", "1", "2.0"
"Source", "0002", "Texas", "10", "1.0"
"Source", "0002", "Texas", "20", "2.0"

What is the best way to apprach this problem? I did the following
var list = from c in doc.decentents()
where !c.HasElements()
select c;

with this I can get everything except location properly, I am sure I
am missing something simple here.
Thanks.
 
CSharper said:
I have an xml file the following

<?xml version="1.0" encoding="utf-8" ?>
<Source Met="Source">
<Name SourceName="0001">
<Location>Texas</Location>
<Values>
<Value id="1" Amount="1.0" />
<Value id="2" Amount="2.0" />
</Values>
</Name>
<Name SourceName="0002">
<Location>Texas</Location>
<Values>
<Value id="10" Amount="1.0" />
<Value id="20" Amount="2.0" />
</Values>
</Name>
</Source>

I want to convert this XML into a normalised string and I would like
the string result to be
"Source", "0001", "Texas", "1", "1.0"
"Source", "0001", "Texas", "1", "2.0"
"Source", "0002", "Texas", "10", "1.0"
"Source", "0002", "Texas", "20", "2.0"

What is the best way to apprach this problem? I did the following
var list = from c in doc.decentents()
where !c.HasElements()
select c;

with this I can get everything except location properly, I am sure I
am missing something simple here.

You need to go "up" from Value to Values, then "up" from Values to
Name, then *down* again to find the Location.

Here's a short but complete program which does it all:

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("test.xml");

var entries =
from valueElt in doc.Descendants("Value")
let nameElt = valueElt.Parent.Parent
select new { Source=(string) nameElt.Parent.Attribute("Met"),
Name=(string)nameElt.Attribute("SourceName"),
Location=(string)nameElt.Element("Location"),
Id=(int) valueElt.Attribute("id"),
Amount=(decimal) valueElt.Attribute("Amount") };

foreach (var entry in entries)
{
Console.WriteLine(entry);
}
}
}
 
Back
Top