2

最初に、これを行う最善の方法が何であるかはわかりませんが、これが私のシナリオです。テスト スイートで読み取る必要がある多数のアカウントがあります。それらをapp.configファイルにxml形式で保存し、そのようにアカウントを読み取るつもりでした。これが最善の方法ですか?代わりに JSON を使用する必要がありますか? とにかく、私はここでこの方法に従おうとしました:

http://www.codeproject.com/Articles/6730/Custom-Objects-From-the-App-Config-file 私は使用していますがConfigurationManager.GetSection(); ConfigurationSettings.GetConfig()非推奨であるため、代わりに。ただし、使用しようとすると常にヌルポインター例外が発生するカスタム ConfigSectionHandler をダウンロードする必要がありました。

解析しようとしている xml の形式は次のとおりです。

<testConfig>
    <accounts>
        <account>
            <name>foo</name>
            <password>bar</password>
            <description/>cool account</description>
        </account>
        <account>
            <name>bar</name>
            <password>foo</password>
            <description/>uncool account</description>
        </account>
    </accounts>
</testConfig> 

それを解析して Account オブジェクトのリストにできればいいのですが、既に Account クラスが定義されています。

4

1 に答える 1

4

これを試してください:

var xDoc = XDocument.Parse(xmlString);XML を文字列にロードして XDocument に配置する場合に使用します。ただし、単純にvar xDoc = XDocument.Load(@"XMLPathGoesHere");xml を直接ロードするために使用できます。

サンプル アカウント オブジェクト:

public class Account
{
    public string Name { get; set; }
    public string Password { get; set; }
    public string Description { get; set; }
}

次に、以下の LINQ クエリを使用します。

var accounts = (from xElem in xDoc.Descendants("account")
                select new Account()
                {
                    Name = xElem.Element("name").Value ?? string.Empty,
                    Password = xElem.Element("password").Value ?? string.Empty,
                    Description = xElem.Element("description").Value ?? string.Empty
                }).ToList();

また、XML の<description/>uncool account</description>. 私はこの部分があるべきだと思います<description>uncool account</description>

LINQ Pad Dump の結果

ここに画像の説明を入力

于 2013-05-30T01:13:50.960 に答える