1

how can I access data coming from an XML File into variables?

<RESULTS>
    <ROW>
        <COLUMN NAME="OM_USER"><![CDATA[TEXT]]></COLUMN>
        <COLUMN NAME="LASTNAME"><![CDATA[TEXT]]></COLUMN>
        <COLUMN NAME="FIRSTNAME"><![CDATA[TEXT]]></COLUMN>
        <COLUMN NAME="PHONE"><![CDATA[TEXT]]></COLUMN>
    </ROW>
</RESULTS>

this is what i tried but the output is weired

XDocument xmlDocument = XDocument.Load(@"PATH");

var xElement = xmlDocument.Element();

if (xElement != null)
{
    foreach (var child in xElement.Elements())
    {
       Console.WriteLine(child.Name + ": " + child.Value);
    }
 }

My Output come like this:

ROW: TEXTEXTTEXTTEXT ROW: TEXTEXTTEXTTEXT ROW: TEXTEXTTEXTTEXT ROW: TEXTEXTTEXTTEXT

Thanks for any help =)

  • Did you use google? did you try something already? – sommmen Sep 10 '20 at 11:24
  • I did google smth, my problem is dat i get the data but not seperated it comes like this: ROW: TEXTTEXTTEXTTEXT ROW: TEXTTEXTTEXTTEXT and so on – CodeWithBrain Sep 10 '20 at 11:26
  • 3
    hi @CodeWithBrain, welcome to stackoverflow. first of all please see [ask]. and fyi, in the past we have [linq to xml](https://stackoverflow.com/a/685590/4648586) for easy xml reading and [using xml reader](https://stackoverflow.com/a/676280/4648586). see if those two helps. if your problem is specific please provide [mcve]. – Bagus Tesa Sep 10 '20 at 11:26

1 Answers1

0

The problem that you are facing is that you are a level too high in the xml tree. By stating

var xElement = xmlDocument.Elements();

You get all the elements from the top of the xdocument, which is the root named "RESULTS"

Your foreach is looping over all the child's of the "RESULTS" element which is only "ROW". If you the specify that you want to print the name of the child (ROW) and its value you get all the text that element "ROW" and all it's children have. If you use the debugger you will see this content.

By changing your code to something simular below you will get the correct outcome

const string msg = "<RESULTS><ROW><COLUMN NAME=\"OM_USER\"><![CDATA[TEXT]]></COLUMN><COLUMN NAME=\"LASTNAME\"><![CDATA[TEXT]]></COLUMN><COLUMN NAME=\"FIRSTNAME\"><![CDATA[TEXT]]></COLUMN><COLUMN NAME=\"PHONE\"><![CDATA[TEXT]]></COLUMN></ROW></RESULTS>";

XDocument xmlDocument = XDocument.Parse(msg);

//get the first element named ROW from the xdocument.
var xElement = xmlDocument.Descendants().First(x => x.Name == "ROW");

if (xElement != null)
{
   //Loop through the childs of ROW
   foreach (var child in xElement.Elements())
   {
      //Find the first attribute in the child element which is named NAME.
      var childAttrName = child.Attributes().First(x => x.Name == "NAME");
      //Print the value of the attribute called name and the value of the element.
      System.Console.WriteLine(childAttrName.Value + " : " + child.Value);
   }
}
martijn
  • 485
  • 2
  • 9