Click here to Skip to main content
15,899,825 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have an XML file which looks like this.
XML
<<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.
C#
<pre lang="c#">
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
Posted
Updated 8-Nov-13 14:28pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900