dlarkin77
dlarkin77

Reputation: 879

Linq to XML - Problem selecting elements

<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>

Hi,

I need to get elements where

So, based on the XML snippet I want to get the Adjstmnet and InvGd elements.

The closest I can get is

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

but that doesn't include the InvGd element.

Any ideas on what I need to change/add?

Thanks,

David

Upvotes: 0

Views: 187

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167541

Using xe.Descendants() instead of xe.Elements() should help. Of course you also need to add the check about the parent element.

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

Upvotes: 1

Related Questions