none
Grouping the XML attributes based on attribute value by using VB.Net RRS feed

  • Question

  • Below is the my original XML file and requirement details.

    <?xml version="1.0" encoding="utf-8"?>
    <Payments>
      <P P1="492" P2="BTX" P3="492V" P4="1" P5="A" ID="A" Amount="40"  P8="20" />
      <P P1="492" P2="BTX" P3="492V" P4="1" P5="A" ID="A" Amount="0" P8="10" />
      <P P1="492" P2="BTX" P3="492V" P4="1" P5="A" ID="A" Amount="0"  P8="30" />
      <P P1="492" P2="BTX" P3="492V" P4="2" P5="B" ID="B" Amount="50"  P8="50"/>
      <P P1="492" P2="BTX" P3="492V" P4="2" P5="B" ID="B" Amount="0"  P8="50"/>
      <P P1="492" P2="BTX" P3="492V" P4="2" P5="B" ID="B" Amount="0"  P8="50"/>
    </Payments>



    I am looking for:

    • Based on ID and Amount attribute value, we need to create child attributes.
    • Example: For ID = "A", we have three records and only for one record we have amount  = "40", Here we need to create another TAG for child records.

    I am attaching the expected result as:

    <?xml version="1.0" encoding="utf-8"?>
    <Payments>
      <P P1="492" P2="BTX" P3="492V" P4="1" P5="A" ID="A" Amount="40"  P8="20" >
        <R P1="492" P2="BTX" P3="492V" P4="1" P5="A" ID="A" Amount="0" P8="10" />
        <R P1="492" P2="BTX" P3="492V" P4="1" P5="A" ID="A" Amount="0"  P8="30" />
      </P>
      <P P1="492" P2="BTX" P3="492V" P4="2" P5="B" ID="B" Amount="50"  P8="50">
        <R P1="492" P2="BTX" P3="492V" P4="2" P5="B" ID="B" Amount="0"  P8="50"/>
        <R P1="492" P2="BTX" P3="492V" P4="2" P5="B" ID="B" Amount="0"  P8="50"/>
      </P>
    </Payments>

    Could you please look into this. Let me know if you need any further details.

    Thank you in advance.

    Wednesday, September 18, 2019 5:20 PM

All replies

  • Hi,
    try this console demo:

    Module Module1
      Sub Main()
        Try
          Call (New Demo).Execute()
        Catch ex As Exception
          Console.WriteLine(ex.ToString)
        End Try
        Console.WriteLine("Continue enter key")
        Console.ReadKey()
      End Sub
    
      Friend Class Demo
    
        Private filePath As String = "Module26XMLFile1.xml"
    
        Friend Sub Execute()
          Dim input = XElement.Load(filePath)
          Dim output As New XElement("Payments")
          Dim q1 = From item1a In input.<P> Where item1a.@Amount <> "0"
          For Each item1b In q1
            Dim q2 = From item2a In input.<P> Where item2a.@Amount = "0" AndAlso item2a.@ID = item1b.@ID
            For Each item2b In q2
              item1b.Add(item2b)
            Next
            output.Add(item1b)
          Next
          Console.WriteLine(output)
        End Sub
    
      End Class
    
    End Module


    --
    Best Regards / Viele Grüße
    Peter Fleischer (former MVP for Developer Technologies)
    Homepage, Tipps, Tricks



    Thursday, September 19, 2019 3:01 AM