Linq到xml。确定标签的结尾

时间:2015-01-30 08:59:46

标签: c# xml linq

我有一块xml如下:

<side>
 <category>
   <title>Head</head>
   <item> Mister a </item>
 </category>
 <category>
   <title>Head</head>
   <item> Mister x </item>
   <item> Mister y </item>
 </category>
</side>

我正在为每个类别标题和项目进行恢复,并且一旦到达类别的末尾,就会放置一个允许分隔类别的分隔符。现在我可以很好地恢复每个类别标题和项目,但我不能在两个类别之间放置分隔符

这是我在C#中的代码:

foreach (XElement node in doc.Descendants("category").Elements())
        {

                if (node.Name.LocalName.Equals("titre"))
                {
                    layout.Records.Add(new XMLRecord()
                    {
                        Type = "Titre",
                        Contenu = node.Value
                    });

                }
                else if (node.Name.LocalName.Equals("item"))
                {
                    layout.Records.Add(new XMLRecord()
                    {
                        Type = "Item",
                        Contenu = node.Value
                    });

                }
                else if (node.Name.LocalName.Equals("item") && node.NextNode == null)
                {
                    layout.Records.Add(new XMLRecord()
                    {
                        Type = "Item",
                        Contenu = node.Value
                    });

                    layout.Records.Add(new XMLRecord()
                    {
                        Type = "Separateur",
                        Contenu = ""
                    });


                }




        }
        return layout.Records;

1 个答案:

答案 0 :(得分:1)

这应该是 -

foreach (XElement node in doc.Descendants("category").Elements())
        {
            if (node.Name.LocalName.Equals("titre"))
            {
                layout.Records.Add(new XMLRecord()
                {
                    Type = "Titre",
                    Contenu = node.Value
                });
            }
            //This check requires here because at every item you won't get NextNode null except last one.
            else if (node.Name.LocalName.Equals("item") && node.NextNode == null)
            {
                layout.Records.Add(new XMLRecord()
                {
                    Type = "Item",
                    Contenu = node.Value
                });

                layout.Records.Add(new XMLRecord()
                {
                    Type = "Separateur",
                    Contenu = ""
                });
            }
            else if (node.Name.LocalName.Equals("item"))
            {
                layout.Records.Add(new XMLRecord()
                {
                    Type = "Item",
                    Contenu = node.Value
                });

            }
        }
        return layout.Records;