XmlでSystem.Linq.Dynamicを使用する方法の基本的な例が必要です。以下は、動的Linqに変換したい機能ステートメントです。
XElement e = XElement.Load(new XmlNodeReader(XmlDoc));
var results =
from r in e.Elements("TABLES").Descendants("AGREEMENT")
where (string)r.Element("AGRMNT_TYPE_CODE") == "ISDA"
select r.Element("DATE_SIGNED");
foreach (var x in results)
{
result = x.Value;
break;
}
ここに私が使用しているアプローチがあります:
string whereClause = "(\"AGRMNT_TYPE_CODE\") == \"ISDA\"";
string selectClause = "(\"DATE_SIGNED\")";
var results = e.Elements("TABLES").Descendants<XElement>("AGREEMENT").
AsQueryable<XElement>().
Where<XElement>(whereClause).
Select(selectClause);
foreach (var x in results)
{
result = (string)x;
break;
}
エラーなしで実行されますが、結果は生成されません。
これをhttp://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-queryにある標準的な例と同様にコーディングしようとしています-library.aspx(構築された文字列がデータベースに適用されます):
Dim Northwind as New NorthwindDataContext
Dim query = Northwind.Products _
.Where("CategoryID=2 and UnitPrice>3") _
.OrderBy("SupplierId")
GridView1.Datasource = query
GridView1.Databind()
何が欠けていますか?
ようやく動作しました。現時点ではXmlでの使用を意図したものでさえないと確信しているため、元のアプローチを放棄しました。私はその声明に反論するためにどこにも投稿されたことはほとんどありません。代わりに、 この質問に対するJon Skeetの回答を私の回答の基礎として使用しました。
XElement e = XElement.Load(new XmlNodeReader(XmlDoc));
List<Func<XElement, bool>> exps = new List<Func<XElement, bool>> { };
exps.Add(GetXmlQueryExprEqual("AGRMNT_TYPE_CODE", "ISDA"));
exps.Add(GetXmlQueryExprNotEqual("WHO_SENDS_CONTRACT_IND", "X"));
List<ConditionalOperatorType> condOps = new List<ConditionalOperatorType> { };
condOps.Add(ConditionalOperatorType.And);
condOps.Add(ConditionalOperatorType.And);
//Hard-coded test value of the select field Id will be resolved programatically in the
//final version, as will the preceding literal constants.
var results = GetValueFromXml(171, e, exps, condOps);
foreach (var x in results)
{
result = x.Value;
break;
}
return result;
...
public static Func<XElement, bool> GetXmlQueryExprEqual(string element, string compare)
{
try
{
Expression<Func<XElement, bool>> expressExp = a => (string)a.Element(element) == compare;
Func<XElement, bool> express = expressExp.Compile();
return express;
}
catch (Exception e)
{
return null;
}
}
public static Func<XElement, bool> GetXmlQueryExprNotEqual(string element, string compare)
{
try
{
Expression<Func<XElement, bool>> expressExp = a => (string)a.Element(element) != compare;
Func<XElement, bool> express = expressExp.Compile();
return express;
}
catch (Exception e)
{
return null;
}
}
private IEnumerable<XElement> GetValueFromXml(int selectFieldId, XElement elem,
List<Func<XElement, bool>> predList, List<ConditionalOperatorType> condOpsList)
{
try
{
string fieldName = DocMast.GetFieldName(selectFieldId);
string xmlPathRoot = DocMast.Fields[true, selectFieldId].XmlPathRoot;
string xmlPathParent = DocMast.Fields[true, selectFieldId].XmlPathParent;
IEnumerable<XElement> results = null;
ConditionalOperatorType condOp = ConditionalOperatorType.None;
switch (predList.Count)
{
case (1):
results =
from r in elem.Elements(xmlPathRoot).Descendants(xmlPathParent)
where (predList[0](r))
select r.Element(fieldName);
break;
case (2):
CondOp = (ConditionalOperatorType)condOpsList[0];
switch (condOp)
{
case (ConditionalOperatorType.And):
results =
from r in elem.Elements(xmlPathRoot).Descendants(xmlPathParent)
where (predList[0](r) && predList[1](r))
select r.Element(fieldName);
break;
case (ConditionalOperatorType.Or):
results =
from r in elem.Elements(xmlPathRoot).Descendants(xmlPathParent)
where (predList[0](r) || predList[1](r))
select r.Element(fieldName);
break;
default:
break;
}
break;
default:
break;
}
return results;
}
catch (Exception e)
{
return null;
}
}
ただし、このアプローチは明らかに完璧とはほど遠いものです。
任意のアイデアや提案をいただければ幸いです。
ここには実際に2つの問題があります。それはwhere句です。
("AGMNT_TYPE_CODE") == "ISDA"
...もちろん、両方とも文字列であるため、 false
と評価されます。
2番目の問題は、 ExpressionParser
スコープが制限されていることです。これは、事前定義された型のセットに対してのみ比較を実行できます。動的ライブラリを再コンパイルして、いくつかの追加の型を許可する( ExpressionParser
型のpredefinedTypes
静的フィールドを変更してこれを行うことができます)か、事前定義型のチェックを削除する必要があります(これは以前に行ったことです)。
Expression ParseMemberAccess(Type type, Expression instance)
{
// ...
switch (FindMethod(type, id, instance == null, args, out mb))
{
case 0:
throw ParseError(errorPos, Res.NoApplicableMethod,
id, GetTypeName(type));
case 1:
MethodInfo method = (MethodInfo)mb;
//if (!IsPredefinedType(method.DeclaringType)) // Comment out this line, and the next.
//throw ParseError(errorPos, Res.MethodsAreInaccessible, GetTypeName(method.DeclaringType));
if (method.ReturnType == typeof(void))
throw ParseError(errorPos, Res.MethodIsVoid,
id, GetTypeName(method.DeclaringType));
return Expression.Call(instance, (MethodInfo)method, args);
default:
throw ParseError(errorPos, Res.AmbiguousMethodInvocation,
id, GetTypeName(type));
}
// ...
}
コメントアウトした行は、事前定義されたタイプのチェックが行われる場所です。
その変更を行ったら、クエリを更新する必要があります( ExpressionParser
はコンパイルされたExpressionParser
構築するため、単に"(\"AGRMNT_TYPE_CODE\") == \"ISDA\""
機能しません。次のようなものが必要です。 :
string where = "Element(\"AGMNT_TYPE_CODE\").Value == \"ISDA\"";