1

LINQ to XMLを使用して、タグを削除してxmlドキュメントに挿入しています。私がよく遭遇する状況の1つは、特定のタグを挿入したい場所を好みますが、その好みが常に満たされるとは限らないということですたとえば、ここでは、同じCalendarCodeを持つ最後の要素の直後に挿入したいと思います。

elements = from e in calendarDocument.Descendants("ExceptionalSessions") where e.Element("CalendarCode") == calendarCode select e;

elements.Last().AddAfterSelf(sessionElement);

ただし、挿入される要素が、そのCalendarCodeを持つそのドキュメントで最初の要素である場合があるため、追加の条件は次のとおりです。

where e.Element("CalendarCode") == calendarCode  

空の結果セットを作成します。その場合、追加の条件なしでクエリを使用したいと思います。これは1回限りのことですが、そのカレンダーコードを含む要素を挿入した後、同じCalendarCodeを含むNEXT要素を最初の要素の後に挿入したいのですが...その場合は、そのクエリを使用します追加の条件。

私はこれを解決するためにいくつかの方法を試しましたが、それらはすべて非常に粗雑で非効率的である可能性があり、私は助けることができませんでしたが、より良い方法があると思います。

彼らがこれに遭遇したことがあれば、誰かが私にアイデアを与えることができますか?

4

1 に答える 1

2

1つのオプションは、条件を評価し、それを追加する前にターゲットを決定することです。明確にするために別の方法を使用します。おそらく次のようなものです(テストされていません)。

private XElement GetCalendarTargetNode(XElement source, XElement calendarCode)
        {
            var exceptionalSessions = source.Descendants("ExceptionalSessions");
            return exceptionalSessions.LastOrDefault(e => e.Element("CalendarCode") == calendarCode) ?? exceptionalSessions.Last();
        }

またはわずかに異なる実装:

private XElement GetCalendarTargetNode(XElement source, XElement calendarCode)
        {
            var exceptionalSessions = source.Descendants("ExceptionalSessions");
            return exceptionalSessions.Where(e => e.Element("CalendarCode") == calendarCode).DefaultIfEmpty(exceptionalSessions.Last()).Last();
        }

そしてそれを使用してください:

var target = GetCalendarTargetNode(calendarDocument, calendarCode);
target.AddAfterSelf(sessionElement);

編集: または追加のメソッドを使用せずに簡略化されたバージョン:

    var exceptionalSessions = calendarDocument.Descendants("ExceptionalSessions");
    var target = exceptionalSessions.Where(e => e.Element("CalendarCode") == calendarCode)
        .DefaultIfEmpty(exceptionalSessions.Last());
    target.Last().AddAfterSelf(sessionElement);
于 2012-07-09T15:53:32.977 に答える