根据正则表达式查找XML值

时间:2017-10-25 16:22:33

标签: c# regex linq linq-to-xml

我有一个配方XML FIle,它具有通配符的值(基于*符号)。我有代码可以确定匹配的值但是没有找到任何结果。

我一直在阅读有关LINQ和正则表达式以及this

的所有内容

我做错了什么?

C#代码

 Regex regEx = new Regex("450455-501", RegexOptions.IgnoreCase);

            XDocument recipefile = XDocument.Load(@"C:\testData\Recipes\Recipes.xml");

            var recipes = (from recipe in recipefile.Descendants("recipe").
               Where(r => regEx.IsMatch(r.Element("partnumber").Value))
                           select new
                           {
                               partnumber = recipe.Element("partnumber").Value,
                               recipename = recipe.Element("recipename ").Value,
                           });

            //print product attributes to the console
            foreach (var recipe in recipes)
            {
                MessageBox.Show("Product Name:    " + recipe.partnumber);
                MessageBox.Show("List Price:      " + recipe.recipename);
            }

XML文件

<?xml version="1.0" encoding="utf-8"?>
<body>
    <recipes>
    <recipe>
        <partnumber value="450455-50*" />
        <recipename value="porkchop" />
    </recipe>
    <recipe>
        <partnumber value="420100-1**" />
        <recipename value="porkchop" />
    </recipe>
    </recipes>
</body>

1 个答案:

答案 0 :(得分:1)

这有效

// Load the recipe
            XDocument doc = XDocument.Load(@"C:\test\Recipes\Recipes.xml");
            string response = "420100-199";

            //Note If you know the result should contain 0 or 1 elements, you can use FirstOrDefault() instead of ToList();
            var results = (from c in doc.Descendants("recipe")
                           from f in c.Descendants("partnumber")
                           where Regex.IsMatch(response ,WildcardToRegex((string)f.Attribute("value")))
                           select c).ToList();


            if (results.Count == 0)
            {
                MessageBox.Show("No Recipe Found  ");
                return;
            }

            else if(results.Count > 1)
            {
                MessageBox.Show("Error: More than 1 recipe matches the part number");

            }

            else
            {
                textBox_recipe.Text = string.Format("{0}", results[0].Element("recipename").Attribute("value").Value);
            }

//使用*符号将通配符部件号转换为兼容的正则表达式的方法

public static string WildcardToRegex(string pattern)
{
    return "^" + Regex.Escape(pattern)
                      .Replace(@"\*", ".*")
                      .Replace(@"\?", ".")
               + "$";
}