I am trying to search or get the xml elements of one file based on a query xml file. This query xml file defines which elements will be searched and retrieve their value. The code below does not find all the elements in the xml file even though the element is there:
Anyone can tell me how can I improve my code, or figure out what is the problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ReadXMLRecursively
{
class Program
{
static void Main(string[] args)
{
doc.Load(@"C:\Requests.xml");
doc2.Load(@"C:XmlLists.xml");
XmlNodeList nList2 = doc2.SelectNodes("//Root/Element");
XmlNodeList nList = doc.SelectNodes("//Root/List");
foreach (XmlNode xmlNode in nList)
{
if (nList2 != null)
foreach (XmlNode n in nList2)
{
if (n.Attributes != null)
{
string val = n.Attributes.GetNamedItem("SourceCol").Value;
if (xmlNode[val] != null)
{
//if (n.Attributes != null) Console.WriteLine(n.Attributes.GetNamedItem("SourceCol").Value);
XmlElement xmlElement = xmlNode[val];
if (xmlElement != null) Console.WriteLine(xmlElement.Name);
}
else
{
Console.WriteLine(val + " not found");
}
}
}
Console.WriteLine("------------- end------------------");
}
}
}
XML File 1
<root>
<list>
<FirstName>Abc</FirstName>
<LastName>LT</LastName>
<Occupatoin>Eng</Occupation>
<BirthDate></BirthDate>
...
</list>
</root>
XML File 2
<root>
<Trainings>
<Java>Ab</Java>
<NET>b</NET>
<SQL>c</SQL>
<Powershell>d</Powershell>
...
</Trainings>
Search the above xml files base on this xml file
<root>
<Element Name="Firstname />
<Element Name="Lastname" />
<Element Name="Occupation" />
<Element Name="Java" />
<Element Name="Net" />
...
</root>
You wrote:
In your example there is just one element with the name “list”, and so you will get in
nListjust one node, with one long string that contains all the children nodes, so you cann’t get them by loop.If you want to get the children of “list” any element in different node you need to change it to:
XmlNodeList nList = doc.SelectNodes("//Root/List/*");