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

标签 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 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> 呢?)

关于c# - 通过linq获取一个属性的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375964/

相关文章:

c# - 在另一个 session 中枚举用户桌面的 Windows

c# - 当我在 WPF Prism 应用程序中使用自定义模式对话框时,出现“没有为此对象定义无参数构造函数”错误

c# - XDocument.Validate 未捕获针对 XSD 的所有错误

xml - 如何访问 pyshark 中嗅探的 http 数据包中包含的 xml 有效负载的文本表示?

c# - 将 CheckBox IsChecked 属性绑定(bind)到 ListView 的 SelectedItems 属性

c# - 异步文件保存等待不 "Await"

java - 使用外部 DTD 中的实体将大型 XML 从 ISO-8859-1 转换为 UTF-8

c#-4.0 - 非静态字段、方法或属性需要对象引用

javascript - Window.Print() 在 Internet Explorer 中抛出权限被拒绝的 JavaScript 运行时异常

WPF : Animating user Control on load