Code that creates XML:
public static string TagInvoice()
{
string InvoiceAll = "";
foreach (var item in QueryDb.ListaPostavkRacuna)
{
XElement Invoice = new XElement("Invoice",
new XElement("Identification",
new XElement("Structure", item.Structure),
new XElement("NrStructure", item.NrStructure)),
new XElement("ItemsDesc",
new XElement("DESC",
new XElement("DESC1","some_value"),
new XElement("DESC2", "ordinary"))));
for (int i = 1; i <= (int)Math.Ceiling(item.item_desc.Length / 35d); i++)
{
int Max = 35,
Min = 35 * i - Max;
if (item.item_desc.Length >= (Min + Max))
{
Min = Max * i - Max;
}
else
{
Max = item.item_desc.Length - (i - 1) * 35;
Min = (i - 1) * 35;
}
XElement TempItemDesc = new XElement("ItemsDesc",
new XElement("Code", item.code_art),
new XElement("DESC",
new XElement("DESC1", item.item_desc.Substring(Min, Max))));
Invoice.Element("ItemsDesc").AddAfterSelf(TempItemDesc);
}
InvoiceAll = InvoiceAll.ToString() + Invoice.ToString();
}
return InvoiceAll;
}
If you look closely you will see i am dividing large string into smaller onces with max 35 length
.
Those smaller strings are then incorporated into TempItemDesc and added to XElement Invoice.
Problem is in order of those added elements. Looks like that The AddAfterSelf method is taking into account only first (originial) <ItemsDesc> so my nodes are added in incorrect order (see below):
Example:
String = "A B C D"
Nodes should be added like:
"A"
"B"
"C"
"D"
They are added:
"D"
"C"
"B"
"A"
Is this expected behaveour, how can i add my nodes to the list in a corret order?
As mentioned in MSDN,
AddAfterSelf, adds the specified content immediately after current node.
You are adding the node after first node. Try this code:
Invoice.Element("ItemsDesc").Last().AddAfterSelf(TempItemDesc);
Related link: XNode.AddAfterSelf Method