I hope you can help :-) I have gotten stuck in trying to use LINQ to read XML file in C#.
This is the XML structure:
<DataBase
xsi:schemaLocation="http://somestuff.new/xml http://somestuff.xsd"
xmlns:ns5="http://somestuff.new/ns5"
xmlns:ns3="http://somestuff.new/ns3"
xmlns:ns2="http://somestuff.new/ns2"
xmlns="http://somestuff.new/ns"
xmlns:xsi="http://somestuff.new/XMLScema-instance"
xmlns:ns4="http://somestuff.new/ns4">
<Cars>
<SmallCars attribute="Something">
<Id>licenceplate</Id>
<Parts attribute="All Parts">
<Extras>
<Gauges xmlns="http://somestuff.new/ns32>
<Speed>100</Speed>
<Rpm>3200</Rpm>
</Gauges>
</Extras>
</Parts>
</SmallCars>
</Cars>
</DataBase>
I want to read the value from Speed and RPM using LINQ but everything I try seem to fail...
This is one of my attempts:
XNamespace ns3 = XNamespace.Get("http://somestuff.new/ns3");
from gaugeElement in extentionElement.Descendants(ns3 + "Gauges")
select new Gauge
{
Speed = tpxElement.Element(ns3 + "Speed") != null ? Convert.ToDouble(tpxElement.Element(ns3 + "Speed").Value) : 0.00,
Rpm = tpxElement.Element(ns3 + "Rpm") != null ? Convert.ToInt32(tpxElement.Element(ns3 + "Rpm").Value) : 0
}
I'm using a Gauge class that has to properties:
public int Speed { get; set; }
public int Rpm { get; set; }
I hope one of you clever guys can provide me with an example on how to get these values or explain why my quest for the values fails :-)
Your query expression is declaring a range variable called gaugeElement
, but you're then using tpxElement
within your code. I'd also use the conversions supplied by XElement
to make your code simpler to read - and I wouldn't personally even use a query expression:
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main(string[] args)
{
var doc = XDocument.Load("test.xml");
XNamespace ns = "http://somestuff.new/ns3";
var gauges = doc
.Descendants(ns + "Gauges")
.Select(x => new { // You'd use new Gauge here
Speed = (double?) x.Element(ns + "Speed") ?? 0.0,
Rpm = (int?) x.Element(ns + "Rpm") ?? 0
});
foreach (var gauge in gauges)
{
Console.WriteLine(gauge);
}
}
}
Output (after fixing your XML):
{ Speed = 100, Rpm = 3200 }
See more on this question at Stackoverflow