问题描述
以下代码正在打印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); }
}
}
推荐答案
在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
.
一个更好的方法是使用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仅打印第一个后代值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!