Чтение нескольких узлов на основе условия - PullRequest
0 голосов
/ 21 декабря 2018

У меня есть следующая структура XML.Это просто извлечение файла, содержащего несколько узлов «PName» в «PList».Я только что показал два здесь в качестве примера.

Вопрос в том, что мне нужно извлечь все узлы, которые имеют значение атрибута классификации "paymenttype" и значение атрибута категории как "Кошелек".Затем извлеките «заголовок» из результатов и сохраните в виде словаря или списка.После извлечения хранилища это список или словарь для сравнения извлеченных узлов.

<PatientDetailsXML>             
 <PList> 
               <PName type="Patient">
            <properties>
                <Room bedType="Auto" />
                <PName title="Joe Beom" PId="1234">
                    <Details>
                        <classification classification="paymenttype" category="Wallet" />
                        <classification classification="Humor" category="None" />
                        <classification classification="Food" category="Fruit" />
                    </Details>
                </PName>
                </properties>
            <childEvents>
            </childEvents>
        </PName>
                <PName type="Patient">
            <properties>
                <Room bedType="Auto" />
                <PName title="John Bair" PId="5678">
                    <Details>
                        <classification classification="paymenttype" category="Found" />
                        <classification classification="Humor" category="None" />
                        <classification classification="Food" category="Fruit" />
                    </Details>
                </PName>
                </properties>
            <childEvents>
            </childEvents>
        </PName>
</PList>
</PatientDetailsXML> 

Я попытался, как показано ниже, но не могу понять, что это правильно:

 XElement root = XElement.Load("patientdetails.xml");
       IEnumerable<XElement> tests =

          from el in root.Elements("PName")
          where ((string)el.Element("properties").Element("PName").Element("Details").Element("classification").Attribute("paymenttype") == "EventType") && (string)el.Element("properties").Element("PName").Element("Details").Element("classification").Attribute("category") == "Wallet")

          select el;  



       foreach (XElement el in tests)
        {

         Console.WriteLine (el);
          }

РЕДАКТИРОВАТЬ (Моя вторая попытка):

XmlTextReader Readers = new XmlTextReader("patientdetails.xml");
       XmlDocument docs = new XmlDocument();
       docs.Load(Readers);


   foreach (XmlNode n in docs.SelectNodes(@"//PName/properties/PName/Details/classification[@classification='paymenttype' and @category='Wallet']"))
   {
                Console.WriteLine(n.ParentNode.ParentNode.OuterXml);
   }

1 Ответ

0 голосов
/ 21 декабря 2018

Я исправил вашу первую попытку (LINQ).Сначала возвращается <PName type="Patient"> из рассматриваемого xml.

IEnumerable<XElement> tests =
    from el in root.Element("PList").Elements("PName")
    let c = el.Descendants("classification")
    where c.Where(x => x.Attribute("classification").Value == "paymenttype"
                    && x.Attribute("category").Value == "Wallet").Any()
    select el;

Затем вы можете выполнить итерацию tests и извлечь то, что хотите.

foreach (var el in tests)
{
    Console.WriteLine(
        el.Element("properties")
          .Element("PName")
          .Attribute("title")
          .Value);
}

Я также исправил ваш второйпопытка (XPath).Будет возвращено значение заголовка <PName title="Joe Beom" PId="1234">.

var query = @"//PName[Details/classification[@classification='paymenttype' and @category='Wallet']]/@title";
foreach (XmlNode n in docs.SelectNodes(query))
{
    Console.WriteLine(n.Value);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...