Showing posts with label Easy. Show all posts
Showing posts with label Easy. Show all posts

Wednesday, April 30, 2014

Easy way to search attribute value in XML

If there are many attributes with same name like below
<root>
      <node name="n1" path="1.jpg"/>
      <node name="n2" path="2.jpg"/>
      <node name="n3" path="3.jpg"/>
      <node name="n4" path="4.jpg"/>
</root>

Then if you want to search node n3 path value in easy method then use the following method

XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
doc.SelectSingleNode("/root/node[@name='n3']").Attributes["path"].Value

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.