从逗号分隔值中选择XElements

时间:2014-06-24 06:52:30

标签: c# xml linq

我在项目中使用LINQ-to-XML,我只想提取逗号分隔字符串中的那些元素,即

以下是XML文件中的示例

<?xml version="1.0" encoding="utf-8"?>
<NewDataSet>
  <Table>
    <Entity>Employee</Entity>
    <EntityID>2857</EntityID>
    .. some more nodes...
    .. some more nodes...
  </Table>
    <Table>
    <Entity>Employee</Entity>
    <EntityID>2856</EntityID>
    .. some more nodes...
    .. some more nodes...
  </Table>
 .......
</NewDataSet>

这是我的XElement

 XElement MainEntities = XElement.Load(strFileName);
 IEnumerable<XElement> EntityElements;
 EntityElements = MainEntities.Elements("Table").Where(xtab => (string)xtab.Element("Entity").Value == "Employee");

和逗号分隔的字符串是

var filter = new List<string> { strEmployeeIds };

我试过

EntityElements = MainEntities.Elements("Table").Where(xtab => (string)xtab.Element("Entity").Value == "Employee" && filter.Contains((string)xtab.Element("EntityID").Value));

但它不起作用......

我如何才能获得filter的{​​{1}}中的那些元素;

2 个答案:

答案 0 :(得分:2)

假设strEmployeeIds定义如下:

string strEmployeeIds = "1,2,3";

您需要拆分字符串以制作列表:

string[] filter = strEmployeeIds.Split(',');

答案 1 :(得分:1)

你的意思是这样的:

var filter = "1,2,3,4";
EntityElements = 
        MainEntities.Elements("Table")
                    .Where(xtab => 
                            (string)xtab.Element("Entity").Value == "Employee" && 
                             filter.Split(new[]{","}, StringSplitOptions.RemoveEmptyEntries)
                                   .Contains((string)xtab.Element("EntityID").Value)
                           );