Поиск атрибута по его значению - PullRequest
1 голос
/ 06 апреля 2020

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

<?xml version="1.0" encoding="utf-8"?>
<root>
  <Communication Id ="456">
    <Person> Ivan Ivanov </Person>
   <Describtion> 
          <Age> 16 </Age>
          <Place> Moscow </Place>
          <Key Name ="Language"> English </Key>
          <Key Name ="Profession"> Doctor </Key>
    </Describtion>  
  </Communication>

  <Communication Id ="1010">
    <Person> Petr Petrov </Person>
    <Describtion>
          <Age> 21 </Age>
          <Place> St.Peterburg </Place>
          <Key Name ="Language"> Français </Key>
          <Key Name ="Profession"> Ingeneer </Key>
    </Describtion>  
  </Communication>
</root>

Есть список тегов Key с атрибутом Name, который имеет другое значение. Это значение определяет, в какую переменную будет записано значение между тегами. Как мне написать алгоритм для такого поиска?

Ответы [ 3 ]

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

Попробуйте с XmlDocument

public static string getNodeValue(XmlDocument xmldoc, string id, string key)
{
    return xmldoc.SelectSingleNode($"root/Communication[@Id='{id}']/Describtion/Key[@Name='{key}']")
                 .InnerText
                 .Trim();
}

Использование

var xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
Console.WriteLine(getNodeValue(xmlDoc, "456", "Language"));
Console.WriteLine(getNodeValue(xmlDoc, "1010", "Language"));

Выход

English
Français
0 голосов
/ 06 апреля 2020

Я использовал Xml Linq вместе со словарем и IEquatable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);
            reader.ReadLine();  //allow unicode characters
            XDocument doc = XDocument.Load(reader);

            List<Person> people = doc.Descendants("Communication").Select(x => new Person()
            {
                id = (int)x.Attribute("Id"),
                name = (string)x.Element("Person"),
                age = (int)x.Descendants("Age").FirstOrDefault(),
                place = (string)x.Descendants("Place").FirstOrDefault(),
                language = ((string)x.Descendants("Key").Where(y => (string)y.Attribute("Name") == "Language").FirstOrDefault()).Trim(),
                profession = ((string)x.Descendants("Key").Where(y => (string)y.Attribute("Name") == "Profession").FirstOrDefault()).Trim()
            }).ToList();

            Dictionary<Person, List<Person>> dict = people
                .GroupBy(x => x, y => y)
                .ToDictionary(x => x.Key, y => y.ToList());

            List<Person> results = dict[new Person() { language = "English", profession = "Doctor" }].ToList();

        }
    }
    public class Person : IEquatable<Person>
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
        public string place { get; set; }
        public string language { get; set; }
        public string profession { get; set; }

        public Boolean Equals(Person other)
        {
            return
                (language == other.language) && (profession == other.profession);
        }
        public override int GetHashCode()
        {
            return (language + "^" + profession).GetHashCode() ;
        }

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

Вы можете искать вот так.

xmlDoc.SelectNodes("root/Communication/Describtion/Key[@Name=\"Language\"][text()=\" English \"]")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...