XElemenet AddAfterSelf不添加到最后一个节点

时间:2017-04-19 12:00:14

标签: c# xml xelement

创建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;
    }

如果你仔细观察,你会看到我将大字符串分成较小的on和最大35 length。 然后将那些较小的字符串合并到 TempItemDesc 中,并添加到 XElement Invoice。

问题依赖于那些添加的元素。看起来 AddAfterSelf 方法仅考虑在内 第一个(原创)&lt; ItemsDesc &gt;所以我的节点添加的顺序不正确(见下文):

示例:

String = "A B C D"

节点应添加如下:

"A"
"B"
"C"
"D"

他们被添加:

"D"
"C"
"B"
"A"

这是预期的行为,我如何以正确的顺序将我的节点添加到列表中?

1 个答案:

答案 0 :(得分:0)

如MSDN中所述,

  

AddAfterSelf,在当前节点之后立即添加指定的内容。

您正在第一个节点之后添加节点。 试试这段代码:

Invoice.Element("ItemsDesc").Last().AddAfterSelf(TempItemDesc);

相关链接:XNode.AddAfterSelf Method