如何使用XDocument查询获取正确的元素

时间:2017-02-02 09:40:16

标签: c# xml linq-to-xml

在尝试使用XDocument解析XML文件时,我无法正确获取查询。

我想要的是什么:

给我所有的价值观"姓名"步骤的元素id =" id_3"因此,结果应该是一个列表,其中包含"第1部分的名称,第2部分的名称,第3部分的名称,第4部分的名称

输入XML:

<MyXML>
   <Step id="id_1" type="type1">
     <Name>Some Name</Name>
     <Location>1</Location>
     <Quantity>1</Quantity>
   </Step>
   <Step id="id_2" type="type1">
     <Name>>Some Name</Name>
     <Location>2</Location>
     <Quantity>1</Quantity>
   </Step>
   <Step id="id_3" type="type2">
     <Instruction>This is some text</Instruction>
     <Component>
       <Name>Name of part 1</Name> // --> I want this value
       <Transition_Start>-0.2,0.01,0.0</Transition_Start>
       <Transition_End>0,0.01,0.0</Transition_End>
     </Component>
     <Component>
       <Name>Name of part 2</Name> // --> and this
       <Transition_Start>0.2,0.01,0</Transition_Start>
       <Transition_End>0,0.01,0</Transition_End>
     </Component>
     <Component>
       <Name>Name of part 3</Name> // --> and this
       <Transition_Start>0.05,0.1004,0.0333</Transition_Start>
       <Transition_End>-0.0803,0.1004,0.0333</Transition_End>
     </Component>
     <Component>
       <Name>Name of part 4</Name> // --> and this
       <Transition_Start>-0.0107,0.0383,-0.2328</Transition_Start>
       <Transition_End>-0.0107,0.0383,-0.2328</Transition_End>
     </Component>
   </Step>
 </MyXML>

我试过这样的事情(在Unity3D中)。

IEnumerable<XElement> e_nameOfObjects = 
                from el in myXMLDoc.Root.Elements ("Step")
                where (string)el.Attribute ("id") == "id_" + currentStep
                select el.Elements ("Component");

foreach (XElement e in e_nameOfObjects) {
    Debug.Log (e.Element("Name"));
}

错误消息:

  

无法隐式转换类型    System.Collections.Generic.IEnumerable&GT;&#39;    to System.Collections.Generic.IEnumerable&#39;。显式转换    存在(你是否错过演员表?)

1 个答案:

答案 0 :(得分:1)

您可以使用Elements方法获取所有组件,然后在这些组件中选择Name,如下所示: -

var names = myXMLDoc.Descendants("Step")
            .Where(x => (string)x.Attribute("id") == "id_3")
            .Elements("Component")
            .Select(x => (string)x.Element("Name"));

在这里, names 将返回IEnumerable<string>,您可以轻松地遍历foreach循环。

Working Fiddle.