次の内容の data.xml という名前の xml ファイルがあるとします。
<root>
<record>
<id>1</id>
<name>test 1</name>
<resume>this is the resume</resume>
<specs>these are the specs</specs>
</record>
<record>
<id>2</id>
<name>test 2</name>
<resume>this is the resume 2</resume>
</record>
<record>
<id>3</id>
<name>test 3</name>
<specs>these are the specs 3</specs>
</record>
</root>
これらのフィールド (id、name、resume、または spec) のいずれかに特定の値が含まれているすべてのレコードを検索する必要があります。このコードを作成しました
XDocument DOC = XDocument.Load("data.xml");
IEnumerable<ProductRecord> results = from obj in DOC.Descendants("record")
where
obj.Element("id").Value.Contains(valueToSearch) ||
obj.Element("name").Value.Contains(valueToSearch) ||
obj.Element("resume").Value.Contains(valueToSearch) ||
obj.Element("specs").Value.Contains(valueToSearch)
select new ProductRecord {
ID = obj.Element("id").Value,
Name = obj.Element("name").Value,
Resume = obj.Element("resume").Value,
Specs = obj.Element("specs").Value
};
すべてのレコードにすべてのフィールドがあるわけではないため、このコードは NullReference のエラーをスローします。適用する条件を定義する前に、現在のレコードに特定の要素があるかどうかをテストするにはどうすればよいですか? 元。レコード[@ID=3] には履歴書がありません。
前もって感謝します