0

私はこのXMLを持っています:

<Config>
  <EmpFieldsMap>
    <Employee>
      <Field>
        <Name update = "false">EmpNumber</Name>
      </Field>
      <Field>
        <Name insert = "true">EmpName</Name>
      </Field>
      <Field>
        <Name insert = "true">EmpDesignation</Name>
      </Field>
    </Employee>
  </EmpFieldsMap>
</Config>

私のアプリケーションは、フィールドがこのxmlから取得されるINSERTまたはUPDATEを実行します。各タグには、上記のスニペットに示されているように、insert または update 属性が含まれます。

属性を持つすべてのタグを挿入する場合

insert = "true"

この属性を持たないタグ (この場合は「EmpNumber」) を考慮する必要があります。

更新についても同様です。

このコードは、insert 属性が true に設定されたすべてのタグを提供します。

insertTags = from p in xml.Element("Config").Element("EmpFieldsMap").Elements("Field")
             where p.Element("Name").Attribute("insert") != null 
             && p.Element("Name").Attribute("insert").Value == "true"
             select p.Element("Name").Value;

null のチェックを削除する

insertTags = from p in xml.Element("Config").Element("EmpFieldsMap").Elements("Field")
             where p.Element("Name").Attribute("insert").Value == "true"
             select p.Element("Name").Value;

与える

オブジェクト参照がインスタンスに設定されていません

エラー。

属性が存在しないタグも含むクエリを作成するのに問題があります。

誰かがこれで私を助けてくれますか?

よろしく。

4

2 に答える 2

1
insertTags = from p in xml.Element("Config").Element("EmpFieldsMap").Elements("Field")
    where (p.Element("Name").Attribute("insert") ?? "true") == "true"
    select p.Element("Name").Value;
于 2013-02-20T04:43:55.363 に答える
0

XPath と Linq を使用すると、さらに簡単になります。

XPathSelectElements(@"Config/EmpFieldsMap/Employee/Field/Name[@insert='true']")

また、この特定の xml では、名前要素のグローバル検索を使用できます。

var insertTags = xdoc.XPathSelectElements(@"//Name[@insert='true']")
                     .Select(n => (string)n);

または、Linq クエリ構文を使用します。

var insertTags = from n in xdoc.Descendants("Name")
                 where (string)n.Attribute("insert") == "true"
                 select (string)n;

ノード値を文字列にキャストすると、ノードが見つからなくても例外はスローされません。単にnull返されます。したがって、そのようなものはすべて必要ありません (これはコンパイルできません):

(p.Element("Name").Attribute("insert") ?? "true") == "true"

もう1つの編集。ブール値を扱っている場合は、文字列の代わりにブール値を使用してください。

var insertTags = from n in xdoc.Descendants("Name")
                 where (bool?)n.Attribute("insert") == true
                 select (string)n;

使い方?Nullable ブールnull値には、欠落している属性の値があります。bool?値を持たないものをブール値と比較すると、 が生成されfalseます。そのため、必要な属性を持ちtrue、その属性を持っている要素のみを取得します。

于 2013-03-05T22:24:54.947 に答える