I have an XML file which looks like this.
<<Services>
<Service>
<Name>Crypto</Name>
<Provider>ABC</Provider>
<Operations>
<Operation>
<Name>Encryption</Name>
<MsgIn>String</MsgIn>
<MsgOut>float</MsgOut>
</Operation>
</Operations>
<Category Platform=".NET" >SVC</Category>
</Service>
</Services>
I need to find a user defined keyword in the above xmlfile.
For example
Case 1: if the keyword is "Service" it should return "Name,Provider,Operations,Category"(basically all the child nodes).
Case 2: if the keyword is "Name" it should return "Crypto"(basically text content if node has no child nodes")
Case 3: if the keyword is "Encryption"(text content), it should return "Name"(parent node)
this is the solution i have till now.
<pre lang="c#">
public String[] search(String XMLURL, String keyword)
{
XmlDocument xml = new XmlDocument();
xml.Load(XMLURL);
XmlNode noderef = xml.DocumentElement;
String[] result = traverse(noderef, keyword);
return result;
}
static String[] traverse(XmlNode node, String keyword)
{
String[] name = new String[100];
int i=0;
while (node.Name != keyword)
{
if (node.HasChildNodes)
{
XmlNodeList xnlist = node.ChildNodes;
foreach (XmlNode xn in xnlist)
{
return traverse(xn, keyword);
}
}
else
{
node = node.NextSibling;
return traverse(node, keyword);
}
}
if(node.HasChildNodes)
{
XmlNodeList xnlistresult= node.ChildNodes;
foreach(XmlNode xnresult in xnlistresult)
{
name[i] = xnresult.Name;
i++;
}
return name;
}
else if(node.NodeType == XmlNodeType.Element)
{
name[0]= node.InnerText;
return name;
}
else
{
name[0]=node.Value;
return name;
}
}
}
}
The above code is working fine for Case 1, but not for Case 2 and 3.
When i debug and if my current node is "Name"(in bold), the property hasChildNodes still comes true, which should be false.
Please let me know what you think of it.
Thanks