【发布时间】:2017-04-19 12:00:14
【问题描述】:
创建 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;
}
如果您仔细观察,您会发现我将大字符串分成较小的一次,最大为35 length。
然后将那些较小的 字符串 合并到 TempItemDesc 并添加到 XElement Invoice。
问题在于那些添加的元素的顺序。看起来 AddAfterSelf 方法只考虑 第一个(原始)ItemsDesc>,所以我的节点添加顺序不正确(见下文):
例子:
String = "A B C D"
节点应该像这样添加:
"A"
"B"
"C"
"D"
它们被添加:
"D"
"C"
"B"
"A"
这是预期的行为吗,我怎样才能以正确的顺序将我的节点添加到列表中?
【问题讨论】:
-
这是
Element(...)方法,它返回给定名称为documented 的first 元素。你可以试试Invoice.Elements("ItemsDesc").Last()。 -
在我看来
Invoice.Add(TempItemDesc)会做你想做的事。