Как проверить, существует ли элемент или элемент в другом элементе, используя LINQ? - PullRequest
0 голосов
/ 27 апреля 2020

Мне нужно получить список клиентов в отдельном файле, для которого значение Product / ProductGroup / ProductGroupName равно «xyz» для примера. Я попытался с приведенным ниже фрагментом, который работает для меня, только если все необходимые узлы присутствуют для всех клиентов.

//get list of required customers
var filteredcustomers = xDoc.Root.Element("CustomerCollection").
                           Elements("Customer").
                           Where(a => a.Element("Product").
                                   Element("ProductGroup").
                                   Element("ProductGroupName").
                                   Value == "xyz");
// create new file
 XDocument xmlOut = new  XDocument ();
 XElement rootNode = new XElement("Root");
 xmlOut.Add(rootNode);
 xmlOut.Root.Add(new XElement("CustomerCollection"));
 xmlOut.Descendants("CustomerCollection").FirstOrDefault().Add(filteredcustomers);
 xmlOut.save("path");

Но в файле есть клиенты, у которых нет узла Product или ProductGroup или сам элемент ProductGroupName отсутствует. В этом сценарии этот запрос не работает, даже если у одного клиента возникают проблемы с ожидаемыми узлами. Как я могу отфильтровать список подходящих клиентов, у которых есть все обязательные поля.

Ниже приведен пример файла xml:

<Root>
    <CustomerCollection>
        <Customer>
            <Product>
                <ProductGroup>
                    <ProductGroupId>123</ProductGroupId>
                    <ProductGroupName>xyz</ProductGroupName>
                </ProductGroup>
            </Product>
        </Customer>
        <Customer>
            <Product>
                <ProductGroup>
                    <!-- ProductGroupName element is Missing-->
                    <ProductGroupId>123</ProductGroupId>
                </ProductGroup>
            </Product>
        </Customer>
        <Customer>
            <Product>
                <!-- ProductGroup element is missing-->
            </Product>
        </Customer>

    </CustomerCollection>
</Root

Заранее благодарю за помощь.

Ответы [ 2 ]

0 голосов
/ 27 апреля 2020

Попробуйте следующее:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("ProductGroup")
                .Where(x => (string)x.Element("ProductGroupName") == "xyz")
                .Select(x => new { id = (string)x.Element("ProductGroupId"), name = (string)x.Element("ProductGroupName") })
                .ToList();
        }
    }
}
0 голосов
/ 27 апреля 2020

Вам необходимо использовать Any, чтобы проверить, существует ли элемент.

var filteredcustomers = xDoc.Root.Element("CustomerCollection").
                            Elements("Customer").Where(a => 
                                a.Element("Product").Elements("ProductGroup").Elements("ProductGroupName").Any() 
                                &&
                                a.Element("Product").Element("ProductGroup").Element("ProductGroupName").Value == "xyz");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...