Wednesday, March 12, 2014

How to read XML in easy way in Win C#

I have an XML like below

<?xml version="1.0" encoding="UTF-8"?>
<xd:xmldiff xmlns:xd="http://schemas.microsoft.com/xmltools/2002/xmldiff" fragments="no" options="IgnoreChildOrder IgnoreNamespaces IgnorePrefixes " srcDocHash="41SGFJBSJ43294" version="1.0">
      <xd:node match="2">
            <xd:change match="@version">5.3.7.0</xd:change>
            <xd:node match="3">
                  <xd:change match="@market">default</xd:change>
            </xd:node>
            <xd:node match="14">
                  <xd:node match="8">
                  <xd:change match="@iconFilename">Icons/fav.ico</xd:change>
            </xd:node>
      </xd:node>
 </xd:xmldiff>

Now to read this. (If this is in in some file)
use like below
first of all add:
using System.Xml;

Now write the below code 
XmlDocument doc1 = new XmlDocument();
doc1.Load(xmlFilePath);

And then 
XmlNodeList rootNodeList = doc1.GetElementsByTagName("xd:change");
foreach (XmlNode nd in rootNodeList)
{
  if(nd.ChildNodes.Count>0)
    Console.WriteLine(nd.Attributes["match"].Value + ", " + nd.ChildNodes.Item(0).Value);
  else
    Console.WriteLine(nd.Attributes["match"].Value);
}

Above code will show match attribute of all "xd:change" node. Either that is Parent Node or Child Node.

No comments:

Post a Comment