Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 向此LINQ to XML代码添加条件/筛选器_C#_.net_Xml_Linq - Fatal编程技术网

C# 向此LINQ to XML代码添加条件/筛选器

C# 向此LINQ to XML代码添加条件/筛选器,c#,.net,xml,linq,C#,.net,Xml,Linq,我有一个XML字符串“booms”: 将XML转换为以下字符串: name: John address: New York City name: Daniel address: Los Angeles name: Joe address: Chicago 问题: 如何将LINQ更改为过滤掉满足某些条件的动臂?例如,我如何筛选出地址包含“New”的繁荣期?在本例中,这将给出字符串: name: John address: New York City 但代码不应仅限于“包含”过滤器。如果条

我有一个XML字符串“booms”:

将XML转换为以下字符串:

name: John
address: New York City

name: Daniel
address: Los Angeles

name: Joe
address: Chicago

问题:

如何将LINQ更改为过滤掉满足某些条件的动臂?例如,我如何筛选出地址包含“New”的繁荣期?在本例中,这将给出字符串:

name: John
address: New York City

但代码不应仅限于“包含”过滤器。

如果条件限制为相等

Dictionary<string, string> conditions = new Dictionary<string, string> { { "name", "John" } };

XDocument document = XDocument.Load(new StringReader(xmlString));

var booms = from boomElement in document.Descendants("boom")
            where conditions.All(condition => (string)boomElement.Element(condition.Key) == condition.Value)  // Where is used to filter the result
            let boomChildren = (from boomElementChild in boomElement.Elements()
                                select String.Format("{0}: {1}",
                                                     boomElementChild.Name.LocalName,
                                                     boomElementChild.Value))
            select String.Join(Environment.NewLine, boomChildren);
var result = String.Join(Environment.NewLine + Environment.NewLine, booms);
Dictionary conditions=新字典{{“name”,“John”};
XDocument document=XDocument.Load(新的StringReader(xmlString));
var booms=来自document.substands(“boom”)中的boomElement
where conditions.All(condition=>(string)boomElement.Element(condition.Key)==condition.Value)//where用于过滤结果
让boomChildren=(来自boomElement.Elements()中的boomElementChild)
选择String.Format(“{0}:{1}”,
boomElementChild.Name.LocalName,
boomElementChild.Value)
选择String.Join(Environment.NewLine,boomChildren);
var result=String.Join(Environment.NewLine+Environment.NewLine,booms);
如果不限于equal(包含、等于),则必须创建一个表示条件的结构

// I've made Condition an abstract class to super any kind of condition.
// Just derive this class with the condition you want (And, Or, Equal, <=, IsNumber, ...)
public abstract class Condition
{
    // A condition is defined by this method. Because a condition is basically: "Does the specified value satisfy the condition?"
    public abstract bool Satisfy(string valueToTest);  
}

// This is the first example of condition.
// I wanted to make the condition immutable (readonly) not to be able to change them.
// So, all parameters of the condition are set during the construction.
public sealed class EqualCondition : Condition
{
    private readonly string value;
    public string Value { get { return value; } }

    public EqualCondition(string value)
    {
        this.value = value;
    }

    public override bool Satisfy(string valueToTest)
    {
        return value == valueToTest;  // Equals condition...
    }
}
public sealed class ContainCondition : Condition
{
    private readonly string value;
    public string Value { get { return value; } }

    public ContainCondition(string value)
    {
        this.value = value;
    }

    public override bool Satisfy(string valueToTest)
    {
        return valueToTest.Contains(valueToTest);  // Contains condition
    }
}

// The dictionary is used to list the conditions applied to each element.
Dictionary<string, Condition> conditions = new Dictionary<string, Condition> { { "name", new EqualCondition("John") } };  
XDocument document = XDocument.Load("test.xml");

var booms = from boomElement in document.Descendants("boom")
            // The next line check where all conditions are satisfied for the corresponding elements
            where conditions.All(condition => condition.Value.Satisfy((string)boomElement.Element(condition.Key)))
            let boomChildren = (from boomElementChild in boomElement.Elements()
                                select String.Format("{0}: {1}",
                                                        boomElementChild.Name.LocalName,
                                                        boomElementChild.Value))
            select String.Join(Environment.NewLine, boomChildren);
var result = String.Join(Environment.NewLine + Environment.NewLine, booms);
//我已将Condition作为一个抽象类,用于对任何类型的Condition进行超级处理。
//只需使用所需的条件(And或Equal,condition.Value.sulfit((string)boomElement.Element(condition.Key)))派生此类
让boomChildren=(来自boomElement.Elements()中的boomElementChild)
选择String.Format(“{0}:{1}”,
boomElementChild.Name.LocalName,
boomElementChild.Value)
选择String.Join(Environment.NewLine,boomChildren);
var result=String.Join(Environment.NewLine+Environment.NewLine,booms);

尚未对此进行测试,但请尝试以下操作:

//string xmlString = ...;
XDocument document = XDocument.Load(new StringReader(xmlString));

var booms = from boomElement in document.Descendants("boom").Where(x => true)
            let boolChildren = (from boomElementChild in boomElement.Elements()
                                select String.Format("{0}: {1}",
                                                     boomElementChild.Name.LocalName,
                                                     boomElementChild.Value))
            select String.Join(Environment.NewLine, boolChildren);
var result = String.Join(Environment.NewLine + Environment.NewLine, booms);

将true替换为您在x上的测试。

我强烈键入以下内容:

public class Boom
{
    string Name { get; set; }
    string Address { get; set; }
    public override string ToString()
    {
        return string.Format("Name: {0}{1}Address: {2}, Name, Environment.NewLine, Address);
    }
}
因此,您的查询将更改为:

XDocument document = XDocument.Load(new StringReader(xmlString));
var booms = 
    document.Descendants("boom")
            .Select(x => new Boom { Name = x.Element("name").Value,
                                    Address = x.Element("address").Value })
            .Where(b => /*filter here!*/);

你能提供这样一个一般结构的例子吗?例如,假设地址是地址——一个逗号分隔的子字符串(多个地址)——我想匹配其中一个子字符串。有可能吗?@roger.james如果我没弄错的话,当然可以。这只是字符串比较;您可能只需要使用
address.Split(“,”)
。要查找与条件匹配的地址,请使用
address.Split(“,”)。其中(…)
。抱歉,我们中的一些人对这些问题的看法不同。@Katana314我不明白你的意思。你在哪里看到“,”@CédricBignon这是他的评论请求。例如,假设地址是地址——一个逗号分隔的子字符串。一个大型的、可扩展的基于类的系统可能是他想要的,但我刚刚指出了他将如何在LINQ表达式中内联实现它。他在评论中要求支持
boom
元素中的任何类型的元素。我不知道的不仅仅是
姓名
地址
@CédricBignon,而且由于OP没有在他的OP中指出这一点,因此没有得到确认。也许他的要求变了?我不知道。至少,现在,他有了选择。
public class Boom
{
    string Name { get; set; }
    string Address { get; set; }
    public override string ToString()
    {
        return string.Format("Name: {0}{1}Address: {2}, Name, Environment.NewLine, Address);
    }
}
XDocument document = XDocument.Load(new StringReader(xmlString));
var booms = 
    document.Descendants("boom")
            .Select(x => new Boom { Name = x.Element("name").Value,
                                    Address = x.Element("address").Value })
            .Where(b => /*filter here!*/);