2

XML ドキュメント (以下の抜粋を参照) があり、3 つの文字列引数 (ユーザー名、ファイル名、ステータス) を渡すメソッドがあります。XML ドキュメントを調べて、ファイル名をファイルの DMC 要素と照合し、status 要素と currentUser 要素の値を、メソッドに渡した userName と status の値に変更するプログラムが必要です。

<dataModule>
    <DMC>DMC-PO-A-49-00-00-00A-012A-C_001.SGM</DMC>
    <techName>Pneumatic and shaft power gas turbine engine</techName>
    <infoName>General warnings and cautions and related safety data</infoName>
    <status>Checked In</status>
    <notes>-</notes>
    <currentUser>-</currentUser>
</dataModule>
<dataModule>
    <DMC>DMC-PO-A-49-00-00-00A-00VA-C_001.SGM</DMC>
    <techName>Pneumatic and shaft power gas turbine engine</techName>
    <infoName>List of Applicable Specifications and Documentation</infoName>
    <status>Checked In</status>
    <notes>-</notes>
    <currentUser>-</currentUser>
</dataModule>
<dataModule>
    <DMC>DMC-PO-A-49-00-00-00A-001A-C_001.SGM</DMC>
    <techName>Pneumatic and shaft power gas turbine engine</techName>
    <infoName>Title page</infoName>
    <status>Checked In</status>
    <notes>-</notes>
    <currentUser>-</currentUser>
</dataModule>

現在、次のコードがあります。これにより、私が何を達成しようとしているのかが明確になることを願っています。これは WinForms プロジェクトであり、Linq を使用してこれを行いたいと考えています。

public static void updateStatus(string user, string file, string status)
{
    XDocument doc = XDocument.Load(Form1.CSDBpath + Form1.projectName + "\\Data.xml");

    var el = from item in doc.Descendants("dataModule")
             where item.Descendants("DMC").First().Value == file
             select item;

    var stat = el.Descendants("status");

    // code here to change the value of the 'status' element text

    var newUser = el.Descendants("currentUser");

    // code here to change the value of the 'currentUser' element text

}
4

1 に答える 1

0

IEnumerable<XElement>Linq クエリが単一の ではなくを返すという事実につまずいたかもしれませんXElement。やりたいことを達成する方法の 1 つを次に示します。

public static void updateStatus(string user, string file, string status)
{
    XDocument doc = XDocument.Load(@"C:\Projects\ConsoleApp\XMLDocument.xml");

    var els = from item in doc.Descendants("dataModule")
              where item.Descendants("DMC").First().Value == file
              select item;

    if (els.Count() > 0)
    {
        XElement el = els.First();
        el.SetElementValue("status", status);
        el.SetElementValue("currentUser", user);

        doc.Save(@"C:\Projects\ConsoleApp\XMLDocument.xml");
    }
}
于 2013-03-20T16:36:51.913 に答える