如何过滤Linq结果只返回选定的XML列

时间:2017-09-12 09:05:57

标签: c# linq linq-to-xml

我想问一下如何过滤Linq结果只返回选定的XML列,根据我的XML,我只想返回EntityIdEntityName,{{的值1}},YA

ReasonText

以下是我的代码:

<TASubmittedFileDT>
  <SubmissionType>ECITESVW</SubmissionType>
  <EntityId>201413671M</EntityId>
  <EntityType>6</EntityType>
  <EntityName>Epic</EntityName>
  <YA>2018</YA>
  <FileName>2018.xml</FileName>
  <Reason>0</Reason>
  <ReasonText>Successful</ReasonText>
  <TotalECI>132961837365</TotalECI>
  <Revenue>3559940928276</Revenue>
</TASubmittedFileDT>

2 个答案:

答案 0 :(得分:1)

添加where子句以检查元素的名称:

HashSet<string> names = new HashSet<string>(new string[]
{
    "EntityId", "EntityName", "YA", "ReasonText"
});

var result = XDocument.Load("data.xml").Root.Descendants()
         .Where(element => names.Contains(element.Name.LocalName)).ToList();

或者在查询语法中:

var result = from element in XDocument.Load("data.xml").Root.Descendants()
             where names.Contains(element.Name.LocalName)
             select element;

节点如果您的xml包含多个TASubmittedFileDT元素,那么您需要一些东西:

var result = XDocument.Load("data.xml").Descendants("TASubmittedFileDT")
                      .Select(element => element.Descendants()
                                                .Where(element => names.Contains(element.Name.LocalName)))
                      .ToList();

答案 1 :(得分:1)

另一种可能的解决方案是将xml反序列化为自定义对象。

var serializer = new XmlSerializer(typeof(SomeModel), new XmlRootAttribute("TASubmittedFileDT"));
var doc = XDocument.Load("example.xml");
var resultingMessage = (SomeModel)serializer.Deserialize(doc.CreateReader());

public class SomeModel
{
    public string EntityId { get; set; }
    public string EntityName { get; set; }
    public int YA { get; set; }
    public string ReasonText { get; set; }
}