Skip to main content
 首页 » 编程设计

c#之通过linq获取一个属性的集合

2024年02月20日50lidabo

我有一个 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> 

我想获取属性“cnumber”。结果:

Chapter={"CHP 1";"CHP 2",....}; 

我未完成的代码:

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”部分开始吗?为什么不直接使用 List<int> 呢?)