按属性值查找 XElement
我有一组 IEnumerables,每个集合都有不同的属性值,对应于我的业务对象上的不同属性。这是我正在查询的 XML 示例:
<SimpleData name="zip">60004</SimpleData>
<SimpleData name="name">ARLINGTON HEIGHTS</SimpleData>
<SimpleData name="state">IL</SimpleData>
<SimpleData name="countyname">COOK</SimpleData>
<SimpleData name="lat">42.1121336684356</SimpleData>
<SimpleData name="lon">-87.9736682731814</SimpleData>
我认为我的 linq2xml lambda 很接近(在搜索 MSDN 和 SO 之后),但我似乎无法正确调整它:
string cityName = simpleData.Where(a => a.Attribute("name").Value == "name").Select(a => a.Value).ToString();
cityName get 的值分配给“System.Linq” .Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]" 而不是 ARLINGTON HEIGHTS
有什么建议吗?谢谢
I have a collection of IEnumerables and each one has a different attribute values that corresponds to a different property on my business object. Here is a sample of the XML that I am querying against:
<SimpleData name="zip">60004</SimpleData>
<SimpleData name="name">ARLINGTON HEIGHTS</SimpleData>
<SimpleData name="state">IL</SimpleData>
<SimpleData name="countyname">COOK</SimpleData>
<SimpleData name="lat">42.1121336684356</SimpleData>
<SimpleData name="lon">-87.9736682731814</SimpleData>
I think my linq2xml lambda is close (after searching MSDN and SO) but I can't seem to tweak it just right:
string cityName = simpleData.Where(a => a.Attribute("name").Value == "name").Select(a => a.Value).ToString();
The value of cityName get's assigned to "System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]" instead of ARLINGTON HEIGHTS
Any suggestions? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或
返回一个
IEnumerable
(Linq 扩展方法几乎总是返回集合而不是单个实例),其中包含name
属性等于name
的所有元素值>。然后我们取第一个,如果它为空,则取null
。另外,该 XML 非常可怕,应该被删除。
or
which returns an
IEnumerable<string>
(Linq extension methods almost always return collections and not single instances) containing all element values whosename
attribute equalsname
. Then we take the first one, ornull
if its empty.Also, that XML is horrendous and should be shot.
如果您有 XML:
加载到 XElement/XDocument SimpleDataList 中,您可以使用 XPath: 进行查询,
但我不确定您是否有一个 XElement 开始或一个简单的 IEnumerable...无论如何..我想我'如果它对您有帮助,我会提到 XPath。
If you have the XML:
loaded in the XElement/XDocument SimpleDataList, you can query with XPath:
But I'm not sure if you have an XElement to start with or a simple IEnumerable... In any case.. i figured I'll mention XPath in case it helps you.