1

次の内容の 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] には履歴書がありません。

前もって感謝します

4

3 に答える 3

0

recordlikeごとに存在しないいくつかのノードの値にアクセスしようとしているため、 NullReferenceException が発生していますspecsobj.Element("specs") != null呼び出す前に確認する必要があります.Value

別の方法として、XPath を使用できます。

var doc = XDocument.Load("test.xml");
var records = doc.XPathSelectElements("//record[contains(id, '2') or contains(name, 'test') or contains(resume, 'res') or contains(specs, 'spe')]");
于 2010-11-07T13:20:53.870 に答える
0

次のような拡張メソッドを記述できます。

public static class XMLExtension
{
    public static string GetValue(this XElement input)
    {
        if (input != null)
            return input.Value;
        return null;
    }

    public static bool XMLContains(this string input, string value)
    {
        if (string.IsNullOrEmpty(input))
            return false;
        return input.Contains(value);
    }
}

以下のように使用します。

IEnumerable<ProductRecord> results = from obj in DOC.Descendants("record")
                                                 where
                                            obj.Element("id").GetValue().XMLContains(valueToSearch) || ...
于 2010-11-07T13:26:54.567 に答える
0

まず、名前空間を使用していないためにクラッシュしていないことに驚いています。多分 c#4.0 はこれをバイパスしましたか?

とにかくやってみる

obj.Descendants("id").Any() ? root.Element("id").Value : null

あれは:

select new ProductRecord {
    ID = obj.Descendants("id").Any() ? root.Element("id").Value : null,
    Name = obj.Descendants("name").Any() ? root.Element("name").Value : null,
    Resume = obj.Descendants("resume").Any() ? root.Element("resume").Value : null
    Specs = obj.Descendants("specs").Any() ? root.Element("specs").Value : null
};
于 2010-11-07T13:27:24.753 に答える