有没有办法结合2个LINQ2XML查询?

时间:2011-09-07 21:36:52

标签: c# xml linq linq-to-xml

var instructions = (from item in config.Elements("import")
select new
{
    name = item.Attribute("name").Value,
    watchFolder = item.Attribute("watchFolder").Value,
    root = item.Element("documentRoot").Value,
    DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
    DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
    TemplateName = item.Element("template").Attribute("template").Value,
    Path = item.Element("path").Attribute("path").Value,
    fields = item.Element("fields").Elements()
}).SingleOrDefault();

var fields = from item in instructions.fields
select new
{
    xpath = item.Attribute("xpath").Value,
    FieldName = item.Attribute("FieldName").Value,
    isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
};

1 个答案:

答案 0 :(得分:0)

我认为这样的事情应该有效。我添加了Select方法来返回匿名类。

var instructions = (from item in config.Elements("import")
select new
{
    name = item.Attribute("name").Value,
    watchFolder = item.Attribute("watchFolder").Value,
    root = item.Element("documentRoot").Value,
    DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
    DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
    TemplateName = item.Element("template").Attribute("template").Value,
    Path = item.Element("path").Attribute("path").Value,
    fields = item.Element("fields").Elements().Select(item => new {
        xpath = item.Attribute("xpath").Value,
        FieldName = item.Attribute("FieldName").Value,
        isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
    }
).SingleOrDefault();

如果您不想使用Select Extension方法,则可以使用LINQ语法。这是一个例子。

var instructions = (from item in config.Elements("import")
select new
{
    name = item.Attribute("name").Value,
    watchFolder = item.Attribute("watchFolder").Value,
    root = item.Element("documentRoot").Value,
    DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
    DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
    TemplateName = item.Element("template").Attribute("template").Value,
    Path = item.Element("path").Attribute("path").Value,
    fields = from e in item.Element("fields").Elements()
             select new {
                 xpath = item.Attribute("xpath").Value,
                 FieldName = item.Attribute("FieldName").Value,
                 isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
             } // End of inner select statement
} // End of outer select statement
).SingleOrDefault();