2011-02-09 149 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