Looping through XML using LINQ / XMLDocument

Hi - Could someone please help me.

I am looking for a simple way to loop through an XML string and all its elements using LINQ, and ouputting each Node / Element / Attribute as it loops through the data.

The XML is listed below. It needs to be dynamic though - no reference to any entity names.
I presume it would be some sort of recursive example.

I basically want to use Console.WriteLine to reproduce each element on screen from the xmlString being read. I do NOT want to use an XmlReader or XmlTextReader for this. Using XMLDocument would also be helpful, although I'd prefer LINQ as from what I've read, it's faster.

Thanks
<ediMessage>
<UNH>
    <unhCode testCode='TST0001'>100</unhCode>
    <unhMessageType>CUSDEC</unhMessageType>
    <unhShortCode>CDSA</unhShortCode>
    <unhInfo>
        <unhInfoName>Paul</unhInfoName>
        <unhInfoSurName>Bunyon</unhInfoSurName>
    </unhInfo>
</UNH>
<static>HELLO</static>
<UCM>
    <ucmNumber>12345</ucmNumber>
    <ucmOrganisation>GreenPeace</ucmOrganisation>
    <ucmIndex>1</ucmIndex>
    <ucmIndexCode>GP</ucmIndexCode>
</UCM>
<UNT>
    <untTotalCode>TAX</untTotalCode>
    <untTotal>135 000 000</untTotal>
</UNT>
<UNT>
    <untTotalCode>REBATE</untTotalCode>
    <untTotal>35 000 000</untTotal>
</UNT>
<UNZ>
    <unzCode>ANT01</unzCode>
    <unzId>1234-908-34544-0001</unzId>
</UNZ>
<UNT>
    <untTotalCode>SAL</untTotalCode>
    <untTotal>100 000</untTotal>
</UNT>
</ediMessage>

Open in new window

djcheekyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fernando SotoRetiredCommented:
Hi djcheeky;

The code snippet below will iterate through all the nodes and write to the console window the following:

Element Name: UNH

Element Name: unhCode    Value: 100
        Attribute Name = testCode    Value = TST0001

Element Name: unhMessageType    Value: CUSDEC

Element Name: unhShortCode    Value: CDSA

Element Name: unhInfo

Element Name: unhInfoName    Value: Paul

Element Name: unhInfoSurName    Value: Bunyon

Element Name: static    Value: HELLO

Element Name: UCM

Element Name: ucmNumber    Value: 12345

Element Name: ucmOrganisation    Value: GreenPeace

Element Name: ucmIndex    Value: 1

Element Name: ucmIndexCode    Value: GP

Element Name: UNT

Element Name: untTotalCode    Value: TAX

Element Name: untTotal    Value: 135 000 000

Element Name: UNT

Element Name: untTotalCode    Value: REBATE

Element Name: untTotal    Value: 35 000 000

Element Name: UNZ

Element Name: unzCode    Value: ANT01

Element Name: unzId    Value: 1234-908-34544-0001

Element Name: UNT

Element Name: untTotalCode    Value: SAL

Element Name: untTotal    Value: 100 000


Fernando

private void button3_Click(object sender, EventArgs e)
{
    XDocument doc = XDocument.Load("Test.xml");
    XElement root = doc.Root;
 
    foreach (XElement element in root.Descendants())
    {
        if (element.HasElements)
        {
            Console.WriteLine("\nElement Name: {0}", element.Name);
        }
        else
        {
            Console.WriteLine("\nElement Name: {0}\tValue: {1}", element.Name, element.Value);
        }
        if (element.HasAttributes)
        {
            foreach (XAttribute attrib in element.Attributes())
            {
                Console.WriteLine("\t\tAttribute Name = {0}\tValue = {1}", attrib.Name, attrib.Value);
            }
        }                
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
djcheekyAuthor Commented:
Hi Fernando and thanks for the great anwer.

Just one thing though - will this work for multiple nested elements, or just one layer. I need something that can work no matter how many levels of nodes / elements there are!

Thanks!
Paolo
0
Fernando SotoRetiredCommented:
Hi djcheeky;

It will returns a collection of the descendant elements for this document or element, in  document order. So every element is returned.

Fernando
0
Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

djcheekyAuthor Commented:
Aah cool  thanks!

Just one more quick question before I go - with XmlReader you hve the Conformance.Fragment Setting that can be applied to the XML - is there something similar for xmlDocument??

Thanks a mill!
0
Fernando SotoRetiredCommented:
Hi djcheeky;

I have not worked much with XML model using the XML classes. I have started using XML when Linq made it simpler to use, create and edit XML documents. So if the question is does Linq to XML allow you to load and work with XML Fragment the answer is Yes. If that is not the question can you post a link to Conformance.Fragment Setting or explain what it is so that I may answer your question correctly.

Fernando
0
djcheekyAuthor Commented:
Thanks Fernando - will do!
0
Fernando SotoRetiredCommented:
Not a problem, glad I was able to help.  ;=)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.