如何通过排除一些在linq中遵循一​​定条件的节点来xml文件?

时间:2015-08-27 12:32:59

标签: c# xml linq

在下面的xml数据中,我需要通过排除包含一些子节点的最后一个节点来读取整个xml数据。

<entity name="account">
    <attribute name="name" />
    <attribute name="accountnumber" />
    <attribute name="primarycontactid" />
    <attribute name="address1_city" />
    <attribute name="telephone1" />
    <attribute name="emailaddress1" />
    <attribute name="accountid" />
    <order attribute="name" descending="false" />
    <filter type="and">
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
    <filter type="or" isquickfindfields="1">
      <condition attribute="name" operator="like" value="{0}" />
      <condition attribute="accountnumber" operator="like" value="{0}" />
      <condition attribute="emailaddress1" operator="like" value="{0}" />
      <condition attribute="telephone1" operator="like" value="{0}" />
      <condition attribute="telephone2" operator="like" value="{0}" />
    </filter>
</entity>

现在如何分别获得以下数据

<filter type="or" isquickfindfields="1">
      <condition attribute="name" operator="like" value="{0}" />
      <condition attribute="accountnumber" operator="like" value="{0}" />
      <condition attribute="emailaddress1" operator="like" value="{0}" />
      <condition attribute="telephone1" operator="like" value="{0}" />
      <condition attribute="telephone2" operator="like" value="{0}" />
</filter>

然后

<filter type="and">
      <condition attribute="statecode" operator="eq" value="0" />
</filter>

最后

<attribute name="name" />
<attribute name="accountnumber" />
<attribute name="primarycontactid" />
<attribute name="address1_city" />
<attribute name="telephone1" />
<attribute name="emailaddress1" />
<attribute name="accountid" />
<order attribute="name" descending="false" />

1 个答案:

答案 0 :(得分:1)

使用XElement.Parse()方法将xml加载到XElement

var root = XElement.Parse("your-xml-string");

要获取过滤器,请使用以下查询:

var orFilter = root.Descendants("filter")
    .FirstOrDefault(e => e.Attribute("type").Value == "or");

过滤器也是如此:

var andFilter = root.Descendants("filter")
    .FirstOrDefault(e => e.Attribute("type").Value == "and");

获取属性元素:

var attributeElements = root.Elements()
    .Where(e => e.Name != "filter");

请注意不要在上面的查询中使用Descendants()方法,因为它还会返回过滤器元素的后代。