0

同じクエリ内から2つの値(コメントの*を参照)を取得するために必要な次のxmlがあります。2つの値が関連付けられており、1つのセットを取得できます() or the other () but not using a single query.

Update I updated the xml below to include 2 nodes that exist under the node and added the namespace

Ideally I would like to get them both in a single query into a Dictionary

<root xmlns="http://www.blah.net/xsd/layout/2003-10-16">
    <header/>
    <movement>
        <movementHeader>
            <desc>xyz</desc>
        </movementHeader>
        <detailHeader>
            <desc>abc</desc>
        </detailHeader>
        <detail>
            <!-- * need this value -->
            <code>90125</code>
            <subDetail>
                <!-- * and need this value at same time -->
                <amount>1200.00</amount>
            </subDetail>
        </detail>
        <detail>
            <!-- * need this value -->
            <code>90126</code>
            <subDetail>
                <!-- * and need this value at same time -->
                <amount>1300.00</amount>
            </subDetail>
        </detail>
        <detail>
            <!-- * need this value -->
            <code>9012</code>
            <subDetail>
                <!-- * and need this value at same time -->
                <amount>1400.00</amount>
            </subDetail>
        </detail>
    </movement>
4

2 に答える 2

3

必要なプロパティを保持する匿名タイプに投影できます。

var results = xdoc.Descendants("detail")
                  .Select( x => new 
                   {
                       Code = x.Element("code").Value,
                       Amount = x.Element("subDetail")
                                 .Element("amount").Value 
                   });

foreach (var item in results)
{
    Console.WriteLine("Code = {0}, Amount = {1}", item.Code, item.Amount);
}

テストされて動作し、期待どおりに3つの結果を返します。

これを辞書に追加するには、次を追加するだけToDictionary()です。

var dict = xdoc.Descendants("detail")
               .Select(x => new
                {
                   Code = x.Element("code").Value,
                   Amount = x.Element("subDetail")
                             .Element("amount").Value
                }).ToDictionary(x => x.Code, x => x.Amount);

編集:

XML名前空間を説明するには、それを宣言して使用する必要があります。以下の例を更新しました。

XNamespace ns = "http://www.blah.net/xsd/layout/2003-10-16";
var dict = xdoc.Descendants(ns + "detail")
               .Select(x => new
               {
                  Code = x.Element(ns + "code").Value,
                  Amount = x.Element(ns + "subDetail")
                            .Element(ns + "amount").Value
               }).ToDictionary(x => x.Code, x => x.Amount);
于 2012-06-19T14:17:13.860 に答える
0
var r = from d in doc.Root.Element("movement").Elements("detail")
        let amount = (string)d.Element("subDetail").Element("amount")
        select new 
        {
            Code = (string)d.Element("code"),
            Amount = Decimal.Parse(amount)
        };
于 2012-06-19T14:19:43.977 に答える