0

我需要找到具有属性 nodeName="Industries" 的 SectionIndex,然后获取该 SectionIndex 中每个 Textpage 元素的属性(id 和 nodeName)

   <SectionIndex nodeName="Industries">
       <Textpage id="1" nodeName="Aerospace"</Textpage>
       <Textpage id="2" nodeName="Construction"</Textpage>
       <Textpage id="3" nodeName="Engineering"</Textpage>
    </SectionIndex>
    <SectionIndex nodeName="Greetings">
       <Textpage id="1" nodeName="Hello"</Textpage>
       <Textpage id="2" nodeName="GoodBye"</Textpage>
       <Textpage id="3" nodeName="Later"</Textpage>
    </SectionIndex>

我的查询看起来像

    var queryServices = from s in xmldoc.Root.Descendants("SectionIndex")
                            where s.Attribute("nodeName").Value == "Industries"                                    
                            select new
                            {
                                ServicesKey = s.Element("umbTextpage").Attribute("id").Value ?? "",
                                NodeName = s.Element("umbTextpage").Attribute("nodeName").Value ?? ""
                            };

它只返回航空航天。任何提示都会很棒。

4

3 回答 3

0

你的问题是你在s价值观中循环,每一个都是 a SectionIndex,但你对孩子们更感兴趣。

您可以从孩子的角度重写它:

var queryServices =
    from s in xmldoc.Root.Descendants("Textpage")
    where s.Parent.Attribute("nodeName").Value == "Industries"
    select new
        {
            ServicesKey = s.Attribute("id").Value ?? "",
            NodeName = s.Attribute("nodeName").Value ?? ""
        };

或者,您可以将其拆分为两个查询:一个获取SectionIndex您感兴趣的查询,然后对其进行第二个查询以提取其子项。

于 2012-10-12T22:04:21.023 回答
0

感谢帮助。显然我错过了我试图解析的 5000 行配置文件中的一条所需信息。

    <root id="-1">
    <SectionIndex id="0" nodeName="Greetings">
         <Textpage id="1" nodeName="Hello"></Textpage>
         <Textpage id="2" nodeName="GoodBye"></Textpage>
         <Textpage id="3" nodeName="Later"></Textpage>
    </SectionIndex>
    <Textpage id="4" nodeName="Services">
        <SectionIndex nodeName="Industries">
             <Textpage id="5" nodeName="Aerospace"></Textpage>
             <Textpage id="6" nodeName="Construction"></Textpage>
             <Textpage id="7" nodeName="Engineering"></Textpage>
        </SectionIndex>
    </Textpage>
    </root>

因此,当我尝试运行建议的查询时,它在 where 部分 do to root 没有 nodeName 时返回空异常错误。关于如何使用属性 nodeName="Industries" 查找 SectionIndex 的任何想法,然后获取该 SectionIndex 中每个 Textpage 元素的属性(id 和 nodeName)。

于 2012-10-15T15:51:11.773 回答
0
 var result = xDoc.Descendants("SectionIndex")
            .Where(e => e.Attribute("nodeName").Value == "Industries")
            .SelectMany(e => e.Descendants()
                                 .Select(x => new
                                     {
                                         ServicesKey = x.Attribute("id").Value,
                                         NodeName = x.Attribute("nodeName").Value
                                     }));
于 2012-10-15T16:04:32.213 回答