C# 通过linq获取属性的集合

C# 通过linq获取属性的集合,c#,xml,c#-4.0,xml-parsing,linq-to-xml,C#,Xml,C# 4.0,Xml Parsing,Linq To Xml,我有一个xml文件 <BOOK bnumber="1" bname="Book"> <CHP cnumber="1"> <VER vnumber="1">This is the sentence 1.</VER> <VER vnumber="2">This is the sentence 2.</VER> <VER vnumber="3">This is t

我有一个xml文件

<BOOK bnumber="1" bname="Book">
    <CHP cnumber="1">
        <VER vnumber="1">This is the sentence 1.</VER>
        <VER vnumber="2">This is the sentence 2.</VER>
        <VER vnumber="3">This is the sentence 3.</VER>
   </CHP>
   <CHP cnumber="2">
        <VER vnumber="1">Hello World 1.</VER>
        <VER vnumber="2">Hello World 2.</VER>
        <VER vnumber="3">Hello World 3.</VER>
        <VER vnumber="4">Hello World 4.</VER>
   </CHP>
   <!--MANY: Thousand records-->
</BOOK>
我的未编译代码:

XDocument xdoc = XDocument.Load("Book.xml");
        var temp = xdoc.Descendants("CHP").Where(x => x.Attribute("cnumber").Value != "0");

谢谢。

看起来您可能需要:

var chapters = xdoc.Descendants("CHP")
                   .Select(x => "CHP " + x.Attribute("cnumber").Value)
                   .ToList();
现在还不清楚为什么需要一个
Where
子句-当然,您给出的示例数据中没有一个
cnumber
为0,或者缺少
cnumber
。如果你需要考虑到这一点,你应该明确地说


(顺便说一句,你真的需要“CHP”部分开始吗?为什么不干脆有一个
列表
?)

看起来你可以使用:

var chapters = xdoc.Descendants("CHP")
                   .Select(x => "CHP " + x.Attribute("cnumber").Value)
                   .ToList();
现在还不清楚为什么需要一个
Where
子句-当然,您给出的示例数据中没有一个
cnumber
为0,或者缺少
cnumber
。如果你需要考虑到这一点,你应该明确地说


(顺便说一句,你真的需要“CHP”部分开始吗?为什么不干脆有一个
列表
?)

什么不起作用?我不太明白你的期望是什么。顺便说一下,你的样本数据格式不正确。您可以用
开始标记,然后用
结束标记,只要更正即可。谢谢提醒。什么不起作用?我不太明白你的期望是什么。顺便说一下,你的样本数据格式不正确。您可以用
开始标记,然后用
结束标记,只要更正即可。谢谢提醒。是的,我只需要“CHP”部分开始。是的,我只需要“CHP”部分开始。