获得一组使用LINQ元素元素、LINQ

2023-09-06 06:43:12 作者:谎言

我有以下的XML片段:

 < XML>
   < ObsCont xCampo =字段1>
      < xTexto>例1< / xTexto>
   < / ObsCont>
   < ObsCont xCampo =场2>
      < xTexto>例2< / xTexto>
   < / ObsCont>
   < ObsCont xCampo =FIELD3>
      < xTexto>例3< / xTexto>
   < / ObsCont>
< / XML>
 

我如何(使用LINQ)获得,例如什么是具有作为父xTexto标签内的xCampo属性场2的ObsCont?

(C#,vb.net,你的选择)

解决方案

 的XDocument XML = XDocument.Parse(@<您的XML>中);
从在xml.Elements域(ObsCont)
其中,field.Attribute(xCampo)= NULL和放大器;!&安培;
field.Attribute(xCampo)。价值==场2
选择field.Element(xTexto)的价值。
 

这会返回一个IEnumerable包含所有的值与您指定的标准类型的字符串。

linq 连接mysql 使用LINQ访问数据库

I have the following piece of XML:

<xml>
   <ObsCont xCampo="field1">
      <xTexto>example1</xTexto>
   </ObsCont>
   <ObsCont xCampo="field2">
      <xTexto>example2</xTexto>
   </ObsCont>
   <ObsCont xCampo="field3">
      <xTexto>example3</xTexto>
   </ObsCont>
</xml>

How do I (using linq) get for example what is inside the xTexto tag that has as parent the ObsCont with the xCampo attribute "field2" ?

(c#, vb.net, your choice)

解决方案

XDocument xml = XDocument.Parse(@"<your XML>");
from field in xml.Elements("ObsCont")
where field.Attribute("xCampo") != null && 
field.Attribute("xCampo").Value == "field2"
select field.Element("xTexto").Value;

This returns an IEnumerable of type string containing all of the values with the criteria that you specified.