получить родительский узел, отфильтрованный по дочернему узлу подуровня, XML - PullRequest
0 голосов
/ 26 сентября 2019

У меня есть следующий XML dataset

<?xml version="1.0" ?>
<productCatalog>
  <catalogName>Freeman and Freeman Unique Catalog 2010</catalogName>
  <expiryDate>2012-01-01</expiryDate>

  <products>
    <product id="1001">
      <productName>Gourmet Coffee</productName>
      <description>The finest beans from rare Chillean plantations.</description>
      <productPrice>0.99</productPrice>
      <inStock>true</inStock>
      <category id ="100">
        <name>Latin Breakfast</name>
        <description>International Range</description>
        <subcategory id ="SUB1000">
          <name>Energy</name>
          <description>blah blah</description>
        </subcategory>
      </category>
    </product>
    <product id="1002">
      <productName>Blue China Tea Pot</productName>
      <description>A trendy update for tea drinkers.</description>
      <productPrice>102.99</productPrice>
      <inStock>true</inStock>
      <category id ="200">
        <name>Asian Breakfast</name>
        <description>Asian Range</description>
        <subcategory id ="SUB1000">
          <name>Organic</name>
          <description>healthy organic food for a longer life</description>
        </subcategory>
      </category>
    </product>
    <product id="1002">
      <productName>Blue China Tea Pot</productName>
      <description>A trendy update for tea drinkers.</description>
      <productPrice>102.99</productPrice>
      <inStock>true</inStock>
      <category id ="300">
        <name>Italian Breakfast</name>
        <description>Roman Breakfast</description>
        <subcategory id ="SUB2000">
          <name>italian</name>
          <description>Roman sttyle breakfast</description>
        </subcategory>
      </category>
    </product>
  </products>
</productCatalog>

Я хочу получить все продукты с подкатегорией id = "SUB1000"

Я написал код

  public static void ProductsFilteredBySubCategory(string path) {
            XElement root = XElement.Load(path);
           IEnumerable<XElement> productElems =   root.Element("products").Elements().Where(e => e.Name == "product" ).Select(s => s);

            IEnumerable<XElement> subcats;

            foreach (var item in productElems){

                Console.WriteLine( item.Element("category").Elements().Where(e => e.Name == "subcategory").Select(s => s.Name) );
            }
        }

но в операторе печати в foreach, похоже, нет продуктов, которые были отфильтрованы. Как мне отфильтровать продукты по требуемому subcategory id?Может быть, я делаю это неправильно ...

Ответы [ 3 ]

0 голосов
/ 26 сентября 2019

Вы идете об этом каким-то окольным путем.Вот как я бы структурировал это:

XDocument document = XDocument.Load(path);

var elements = document.Descendants("subcategory")
                            .Where(i => (string)i.Attribute("id") == "SUB1000")
                            .Select(i => i.Parent.Parent);

foreach(var element in elements)
{
    Console.WriteLine(element);
}

Конечно, здесь я не смотрю на конкретные типы сущностей, а просто предполагаю, что идентификаторы уникальны для того, что вы пытаетесь найти, что будет извлекать правильныеэлементы.

0 голосов
/ 26 сентября 2019

Вы можете использовать следующий код, чтобы получить продукт

 var document = XDocument.Load("pathtothexml");
 var coll = document.Descendants("subcategory").Where(s => s.Attribute("id").Value.Equals("SUB1000")).Ancestors("product");
0 голосов
/ 26 сентября 2019

Descendants может быть полезно в этом случае.

var document = XDocument.Load(path);

var products = document.Descendants("product")
    .Where(product => product.Descendants("subcategory")
                             .Any(sub => sub.Attributes("id")
                                              .Any(id => id.Value == "SUB1000")));

foreach(var product in products)
{
    var subId = product.Attributes("id").Select(id => id.Value).FirstOrDefault();

    Console.WriteLine($"Product: {subId}");
}        
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...