VB XML query for attributes using LINQ

I am trying to learn LINQ and ask a question about an XML request using VB.

My XML:

 <Procedure-Text>
    <A ID="marker1"></A>Do This Procedure
 </Procedure-Text>
 <Procedure-Text>
    <A ID="marker2"></A>Do That Procedure
 </Procedure-Text>

How can I specify my request to get only the procedure text with attribute ID marker2 ? In other words, I need a result string that says Do That Procedure.

thanks

+3
source share
2 answers

Use VB XML Literals:

Dim marker2 = From x In data...<Procedure-Text> _
              Where x.<A>.@ID = "marker2" _
              Select x

The triple point syntax produces "all descendants" of the xml element, i.e. data...<Procedure-Test>will create a list of tags <Procedure-Test>insidedata

XML- " ", x.<A> <A> x. x <Procedure-Test>

, <A>, @attr. <A>.@ID = "marker2" True, ID <A> "marker2"

, x.<A>.@ID " ID <A> x"

<Procedure-Text>, Select x

:

Sub Main()

    Dim data = <doc>
                   <Procedure-Text>
                       <A ID="marker1"></A>Do This Procedure
                   </Procedure-Text>
                   <Procedure-Text>
                       <A ID="marker2"></A>Do That Procedure
                   </Procedure-Text>
               </doc>

    Dim marker2 = From x In data...<Procedure-Text> _
                  Where x.<A>.@ID = "marker2" _
                  Select x

    ' prints the second procedure-text element
    Console.WriteLine(marker2.FirstOrDefault().ToString())

    Console.ReadKey()

End Sub
+6

linq

from x 
in d.Descendants("A") 
where x.Attribute("ID").Value == "marker2" 
select x.NextNode

, A, ID - "marker2", node.

You probably want to do FirstOrDefault () in the resulting enumeration to get an XNode (its actually an XText) that has text in it.

+1
source

Source: https://habr.com/ru/post/1703968/


All Articles