Linq to Xml仅打印第一个后代值 [英] Linq to Xml is printing only first descendant value

查看:79
本文介绍了Linq to Xml仅打印第一个后代值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码正在打印Building Phone,但不在打印uxPhone.
1)也许我应该得到Property后代的集合?
2)这似乎很冗长,是否有简短的形式?

The following code is printing Building Phone but not printing uxPhone.
1) Should I be getting a collection of Property descendants maybe?
2) This seems pretty verbose, is there a shorter form of doing this?

var xmlstr =
        @"<Form>
        <ControlsLayout>
        <Object type='sometype' children='Controls'>
        <Property name='ControlLabel'>BuildingPhone</Property>
        <Property name='Name'>uxPhone</Property>
        </Object>
        </ControlsLayout>
        </Form>";

XElement xelement = XElement.Parse(xmlstr);      
var controls = xelement.Descendants("Object");
foreach (var control in controls)
{
    var xElement = control.Element("Property");
    if (xElement != null)
    {
        var xAttribute = xElement.Attribute("name");
        if (xAttribute != null && xAttribute.Value == "ControlLabel")
            { Console.WriteLine(xElement.Value); }
            if (xAttribute != null && xAttribute.Value == "Name")
            { Console.WriteLine(xElement.Value); }
    }
}

推荐答案

也许我应该得到财产后代的集合?

Should I be getting a collection of Property descendants maybe?

control.Element("Property")中使用Element函数将返回单个元素.您想改为使用Elements.

The use of the Element function in control.Element("Property") returns a single element. You want instead to use Elements.

这似乎很冗长,是否有较短的形式?

This seems pretty verbose, is there a shorter form of doing this?

一个更好的方法是使用Descendants("Property")(在xml中递归搜索并返回指定的<>元素的集合),而不是使用where子句的if语句:

A nicer way all together is to use Descendants("Property") (which searches recursively in your xml and returns the collection of elements of the <> you specified) and instead of if statements to use a where clause:

XElement xelement = XElement.Parse(xmlstr);
var result = from element in xelement.Descendants("Property")
             let attribute = element.Attribute("name")
             where (attribute != null && attribute.Value == "ControlLabel" )||
                   (attribute != null && attribute.Value == "Name" )
             select element.Value;

foreach(var item in result)
    Console.WriteLine(item);

// Building Phone
// uxPhone

这篇关于Linq to Xml仅打印第一个后代值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆