【问题标题】:Get a collection of an attribute by linq通过linq获取一个属性的集合
【发布时间】:2012-07-07 17:23:44
【问题描述】:

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

谢谢。

【问题讨论】:

  • 什么不起作用?我不完全理解你的期望是什么。
  • 顺便说一下,您的示例数据格式不正确。您以&lt;VER&gt; 开始标签并以&lt;/Sentence&gt; 结束标签
  • 刚刚更正了。谢谢提醒。

标签: c# xml c#-4.0 xml-parsing linq-to-xml


【解决方案1】:

看起来你可能会使用:

var chapters = xdoc.Descendants("CHP")
                   .Select(x => "CHP " + x.Attribute("cnumber").Value)
                   .ToList();

不清楚为什么您需要 Where 子句 - 当然,您提供的 sample 数据中没有一个 cnumber 为 0 或缺少 cnumber。如果你需要考虑到这一点,你应该明确地说出来。

(顺便说一句,您真的需要“CHP”部分吗?为什么不直接使用List&lt;int&gt;?)

【讨论】:

  • 是的,我只需要“CHP”部分即可。
猜你喜欢
  • 2012-09-01
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多