【问题标题】:Linq to XML - Problem selecting elementsLinq to XML - 选择元素的问题
【发布时间】:2011-02-09 21:57:36
【问题描述】:
<Invoice type='Component' displayName='Invoice' pluralName='Invoices' Msgversion='1' version='1'>
  <UserData type='SpecialElement'>
    <Something />
  </UserData>
  <From type='SpecialElement'>
    <Something />
  </From>
  <To type='SpecialElement'>
    <Something />
  </To>
  <CdtDbtNoteAmt type='xsd:decimal' />
  <PmtDueDt type='xsd:date' />
  <Adjstmnt>
    <AdjAmt />
    <Rate />
  </Adjstmnt>
  <CpyDplct type='PickList'>
    <Item Text='Copy Duplicate' Value='CODU' />
    <Item Text='Copy' Value='COPY' />
    <Item Text='Duplicate' Value='DUPL' />
  </CpyDplct>
  <InvItems type='ParentElement'>
    <InvGd type='Element'>
      <GdDesc type='xsd:decimal' />
      <QtyVl type='xsd:decimal' />
      <ChrgAmt type='xsd:decimal' />
      <PrceVl type='xsd:decimal' />
    </InvGd>
  </InvItems>
</Invoice>

嗨,

我需要获取元素在哪里

  • type 属性不是 SpecialElement 或 PickList
  • 有子元素
  • 父类的type属性不是ParentElement

所以,基于 XML sn-p,我想获取 Adjstmnet 和 InvGd 元素。

我能得到的最接近的是

var query = from n in xe.Elements()
        let attributeType = n.Attribute("type").Value
        where attributeType != "SpecialElement"
        where attributeType != "PickList"
        where n.HasElements
        select n;

但这不包括 InvGd 元素。

关于我需要更改/添加什么的任何想法?

谢谢,

大卫

【问题讨论】:

  • 废话。编辑器损坏了我的 XML sn-p。如何让它包含整个 sn-p 并保持缩进?
  • 您需要更清楚一点...例如,InvGd 是什么?展示一个完整的小例子和预期的输出。
  • 对不起,我不清楚。我基本上需要得到一个仅包含 2 个元素的列表,即 Adjstmnet 元素 () 和 InvGd 元素 ()

标签: linq-to-xml


【解决方案1】:

使用xe.Descendants() 而不是xe.Elements() 应该会有所帮助。当然还需要加上对父元素的检查。

var query = from el in xe.Descendants()
            let attType = (string)el.Attribute("type")
            let parentType = (string).el.Parent.Attribute("type")
            where attType != "SpecialElement" && attType != "PickList"
                  && el.HasElements
                  && parentType != "ParentElement"
            select el

【讨论】:

  • 非常感谢 Martin,这似乎可以完成这项工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多