1

2 番目のファイルの変更された属性が最初のファイルのオブジェクトの値をオーバーライドする必要がある XML ファイルにマージする方法を探しています。これはlinq to xmlで実行できるようですが、その方法を理解するのに苦労しています。

たとえば、次の 2 つの XML ファイルを見てみましょう。

ファイル 1:

<root>
   <foo name="1">
     <val1>hello</val1>
     <val2>world</val2>
   </foo>
   <foo name="2">
     <val1>bye</val1>
   </foo>
</root>

ファイル 2:

<root>
   <foo name="1">
     <val2>friend</val2>
   </foo>
</root>

望ましい最終結果は、ファイル 2 をファイル 1 にマージし、最終的に

<root>
   <foo name="1">
     <val1>hello</val1>
     <val2>friend</val2>
   </foo>
   <foo name="2">
     <val1>bye</val1>
   </foo>
</root>

サブ 'foo' 要素は、ファイル 1 の値を上書きするファイル 2 の設定値を使用して、それらの 'name' 値によって一意に識別される必要があります。

正しい方向へのポインタは大歓迎です、ありがとう!

4

2 に答える 2

0

値を繰り返して更新するだけですが、これをどの程度一般的にしたいかはわかりません...

class Program
{
    const string file1 = @"<root><foo name=""1""><val1>hello</val1><val2>world</val2></foo><foo name=""2""><val1>bye</val1></foo></root>";

    const string file2 = @"<root><foo name=""1""><val2>friend</val2></foo></root>";

    static void Main(string[] args)
    {
        XDocument document1 = XDocument.Parse(file1);
        XDocument document2 = XDocument.Parse(file2);

        foreach (XElement foo in document2.Descendants("foo"))
        {
            foreach (XElement val in foo.Elements())
            {
                XElement elementToUpdate = (from fooElement in document1.Descendants("foo")
                                            from valElement in fooElement.Elements()
                                            where fooElement.Attribute("name").Value == foo.Attribute("name").Value &&
                                                 valElement.Name == val.Name
                                            select valElement).FirstOrDefault();

                if (elementToUpdate != null)
                    elementToUpdate.Value = val.Value;

            }
        }

        Console.WriteLine(document1.ToString());

        Console.ReadLine();

    }
}
于 2013-02-15T18:58:12.613 に答える
0

次の 2 つから新しい xml を作成できます。

XDocument xdoc1 = XDocument.Load("file1.xml");
XDocument xdoc2 = XDocument.Load("file2.xml");

XElement root =
    new XElement("root",
        from f in xdoc2.Descendants("foo").Concat(xdoc1.Descendants("foo"))
        group f by (int)f.Attribute("name") into foos
        select new XElement("foo",
            new XAttribute("name", foos.Key),
            foos.Elements().GroupBy(v => v.Name.LocalName)
                           .OrderBy(g => g.Key)
                           .Select(g => g.First())));

root.Save("file1.xml");

したがって、最初に選択された 2 番目のファイルの foo 要素は、最初のファイルの foo 要素よりも優先されます (グループ化を行う場合)。

于 2013-02-15T19:36:14.997 に答える