This is something I haven't done before, so I might be doing it wrong to begin with, if I am, please let me know.
I created a root XML file with XDocument with:
public void SaveReceipt(List<ArticleFull> articles)
{
XDocument receipt = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement("FiscalRecipet")
);
...
}
And then with a for loop tried to iterate through the articles
List so I can build a receipt XML file.
for (int i = 0; i < articles.Count; i++)
{
int quantity = 1;
//This while loop just counts how many items are in a row
while(!(i + 1 > articles.Count - 1))
{
if (articles[i].Id == articles[i + 1].Id)
{
quantity++;
i++;
}
else break;
}
var enternode = new XElement("FiscalItem",
new XElement("Name", articles[i].Name.ToString()),
new XElement("Price", articles[i].Price.ToString()),
new XElement("Quantity", quantity.ToString()),
new XElement("TaxGroup", articles[i].TaxGroup)
);
//Code missing here...
}
Now, as stated above, I have absolutely no idea how to connect one the receipt
variable to the enternode
variable.
The end XML file should look something like:
<?xml version="1.0" encoding="UTF-8"?>
<FiscalRecipet>
<FiscalItem>
<Name>Coffee</Name>
<Price>130.0</Price>
<Quantity>1.0</Quantity>
<TaxGroup>2</TaxGroup>
</FiscalItem>
<FiscalItem>
<Name>Chocolate</Name>
<Price>350.0</Price>
<Quantity>2.0</Quantity>
<TaxGroup>3</TaxGroup>
</FiscalItem>
<!-- etc... -->
</FiscalRecipet>
I tried searching for an answer by googling, but I didn't get very lucky, which is why I'm thinking I might be going in a wrong direction(?)
It sounds like you just need:
receipt.Root.Add(enternode);
In other words, adding the new element to the root element of the document.
There are likely to be rather simpler ways of doing all of this using LINQ, btw. I suspect you want something like:
var articlesById = articles
.GroupBy(article => article.Id)
.Select(g => new { Article = g.First(), Count = g.Count() });
XDocument receipt = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement("FiscalRecipet",
articlesById.Select(x => new XElement("FiscalItem",
new XElement("Name", x.Article.Name),
new XElement("Price", x.Article.Price),
new XElement("Quantity", x.Count),
new XElement("TaxGroup", x.Article.TaxGroup))
)
);
That replaces your whole code.
See more on this question at Stackoverflow