2011-02-09 115 views
0
<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> 

嗨,的LINQ to XML - 問題選擇元素

我需要得到元素,其中

  • 類型屬性不是SpecialElement或PICKLIST
  • 有子元素
  • 的父類型屬性不是ParentElement

因此,基於XML片段,我想獲得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元素。

關於我需要更改/添加的任何想法?

感謝,

大衛

+0

廢話。編輯器破壞了我的XML片段。我如何獲得它包括整個片段並保持縮進? – dlarkin77 2011-02-09 12:28:57

+0

你需要更清楚一點......例如,什麼是'InvGd'?顯示一個完整的小例子和預期的輸出。 – 2011-02-09 12:37:55

回答

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