Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ to XML查询以查找父元素名称(如Xc)所在的所有子值#_C#_Xml_Linq - Fatal编程技术网

C# LINQ to XML查询以查找父元素名称(如Xc)所在的所有子值#

C# LINQ to XML查询以查找父元素名称(如Xc)所在的所有子值#,c#,xml,linq,C#,Xml,Linq,假设我有一个类似这样的元素 <Root> <ProductOne> <Size>Large</Size> <Height>2</Height> </ProductOne> <ProductTwo> <Size>Small</Size> <Type>B

假设我有一个类似这样的元素

<Root>
     <ProductOne>
           <Size>Large</Size>
           <Height>2</Height>
     </ProductOne>
     <ProductTwo>
           <Size>Small</Size>
           <Type>Bar</Type>
     </ProductOne>
     <ProductThree>
           <Size>Small</Size>
           <Type>Crate</Type>
           <Color>Blue</Color>
     </ProductOne>
     <SomeOtherStuff>
           <OtherThing>CrazyData</OtherThing>
     </SomeOtherStuff>
</Root>

大的
2.
小的
酒吧
小的
大木箱
蓝色
金龟子
我想查询这些数据,并获得一个IEnumerable字符串,其中包含元素中任何包含单词“Product”的子值(即大小、类型、颜色和许多其他可能的属性)

因此,我的结果列表如下所示

Large 2 Small Bar Small Crate Blue 大的 2. 小的 酒吧 小的 大木箱 蓝色
有人能告诉我如何使用LINQ构造这样的查询吗?

首先,您的xml有很多拼写错误。以下是正确的版本:

var xml = @"
<Root>
 <ProductOne>
       <Size>Large</Size>
       <Height>2</Height>
 </ProductOne>
 <ProductTwo>
       <Size>Small</Size>
       <Type>Bar</Type>
 </ProductTwo>
 <ProductThree>
       <Size>Small</Size>
       <Type>Crate</Type>
       <Color>Blue</Color>
 </ProductThree>
 <SomeOtherStuff>
       <OtherThing>CrazyData</OtherThing>
 </SomeOtherStuff>
</Root>";
这将以
列表的形式将通缉名单返回给您

大的 2. 小的 酒吧 小的 大木箱 蓝色
有没有可能更改xml结构?将
Product(Number)
作为一个元素并不是最干净的解决方案。不幸的是,不是,我只是选择ProductOne作为一个通用示例。实际的元素名称将类似于和我在单词上的匹配。您在第二个和第三个产品中有输入错误:
Bar
谢谢!现在是对的。再次被复制和粘贴所挫败。很抱歉,我在问题窗口中动态地编写XML,这不是一个真实的场景。但这很有效,谢谢!
var list = XElement.Parse(xml)  //parses the xml as an XElement
    .Elements() //gets all elements under the "root" node
    .Where(x => x.Name.LocalName.StartsWith("Product")) // only selects elements that 
                                                        // start with "product"
    .SelectMany(x => x.Elements()) // inside of each of the "product" nodes, select
                                   // all the inner nodes and flatten the results 
                                   // into a single list
    .Select(x => x.Value) //select the node's inner text
    .ToList(); //to list (optional)
Large 2 Small Bar Small Crate Blue