I see a lot of (apparently) working solutions for Xml-Files structured like this:
<Areas>
<Area>
<SetNr>"0"</SetNr>
<X1>"283.06"</X1>
<Y1>"-39.0490"</Y1>
<X2>"289.17"</X2>
<Y2>"-40.8466"</Y2>
<Peak>"285.50"</Peak>
<PeakArea>"44.860"</PeakArea>
<DeltaH>"44.860"</DeltaH>
</Area>
<Area>
<SetNr>"1"</SetNr>
<X1>"277.68"</X1>
<Y1>"-38.0286"</Y1>
<X2>"280.94"</X2>
<Y2>"-39.2697"</Y2>
<Peak>"279.96"</Peak>
<PeakArea>"9.411"</PeakArea>
<DeltaH>"9.411"</DeltaH>
</Area>
</Areas>
For this structure I find many examples (here, there etc) (using innerText, SelectSingleNode, GetElementsByTagName etc) to read one <Area /Area>-Package after the other and accessing the X1/Y1/etc seperately.
But my Xml-File is structured like this:
<Areas>
<Area SetNr="0" X1="283.06" Y1="-39.0490" X2="289.17" Y2="-40.8466" Peak="285.50" PeakArea="44.860" DeltaH="44.860" />
<Area SetNr="1" X1="277.68" Y1="-38.0286" X2="280.94" Y2="-39.2697" Peak="279.96" PeakArea="9.411" DeltaH="9.411" />
</Areas>
For this structure the solutions from above don't work. Can anybody help me?
I am looking for a possibility to do something like this
for each(Area in Areas)
{
mySetNr = Area.SetNr
myX1 = Area.X1
...
...
}
or
mySetNr_0 = Area[0].SetNr
myX1_0 = Area[0].X1
...
...
mySetNr_1 = Area[1].SetNr
myX1_1 = Area[1].X1
...
...
(I am aware that mySetNr_0 etc is a very bad way to handle it, this is just to keep my question as short as possible. In my real code I will obviously work with lists)
CodePudding user response:
I am handling it now like this. It works, but I am not really happy with it tbh:
// Parameters from my function
string xElements = "Areas";
string xElement = "Area";
XDocument xDoc = XDocument.Load(xPath xFile);
foreach (var itemElement in xDoc.Element(xElements).Elements(xElement))
{
var x = itemElement.Attributes();
var xx = x.ToList();
List<string> xAttributes = new List<string>();
List<string> xValues = new List<string>();
string[] xValue = new String[] { };
for (int i = 0; i < x.Count(); i )
{
xAttributes.Add(xx[i].Name.ToString());
xValues.Add(xx[i].Value.ToString());
}
writeRow2Access(dbLocation, dbTable, xAttributes, xValues); // further usage of the values
}
CodePudding user response:
Try this.
var strXml =@"<Areas> "
"<Area SetNr=\"0\" X1=\"283.06\" Y1=\"-39.0490\" X2=\"289.17\" Y2=\"-40.8466\" Peak=\"285.50\" PeakArea=\"44.860\" DeltaH=\"44.860\" /> "
"<Area SetNr=\"1\" X1=\"277.68\" Y1=\"-38.0286\" X2=\"280.94\" Y2=\"-39.2697\" Peak=\"279.96\" PeakArea=\"9.411\" DeltaH=\"9.411\" />"
"</Areas>";
XDocument x = XDocument.Parse(strXml);
var tables = x.Descendants("Area");
foreach (var areaAttributes in tables)
{
Console.WriteLine(areaAttributes.Attribute("SetNr").ToString());
Console.WriteLine(areaAttributes.Attribute("X1").ToString());
};