SOAP and XML Code Example: Traversing XML with the XPath property

Many times a SOAP server will return a value that you need to traverse to find the information that is relevant to what you are doing. Below are some examples of various ways to traverse XML using the XPath properties that exist in both the XML and SOAP components. Note that in the SOAP component XSubTree is a configuration setting instead of a property.

Xml xml = new Xml(); string myXML = "" + "" + "" + "value 1" + "" + "" + "value 2" + "" + "" + ""; xml.InputData = myXML; //Any XPath that begins with a leading "/" is absolute. //If it does not it is relative. xml.XPath = "/root/parent1/child1"; Console.WriteLine(xml.XElement); //outputs child1 xml.XPath = "../child2"; Console.WriteLine(xml.XElement); //outputs child2 xml.XPath = "/"; xml.XPath = "parent1/child1"; Console.WriteLine(xml.XElement); //outputs child1 //output the attributes for the currently selected element for (int i = 0; i < xml.XAttributes.Count; i++) { Console.WriteLine(xml.XAttributes[i].Name + ": " + xml.XAttributes[i].Value); } //output the currently selected element's parent Console.WriteLine(xml.XParent); //outputs parent1 //Output all the children's names and inner text of the currently selected element. xml.XPath = "/root/parent1"; for (int i = 0; i < xml.XChildren.Count; i++) { Console.WriteLine(xml.XChildren[i].Name + ": " + xml.XChildren[i].XText); } xml.XPath = "/root/parent1/child2"; Console.WriteLine(xml.XSubTree); //outputs value 2 //Alternative ways to specify a specific element in the DOM xml.XPath = "/root/parent1/[1]"; Console.WriteLine(xml.XElement); //outputs child1 xml.XPath = "/root/parent1/[last()]"; Console.WriteLine(xml.XElement); //outputs child2 xml.XPath = "/root/parent1/[last()-1]"; Console.WriteLine(xml.XElement); //outputs child1 //There are also some features that help if the XML you are //parsing contains several elements of the same name. myXML = "" + "" + "" + "child1" + "" + "" + "child2" + "" + "" + ""; xml.Reset(); xml.InputData = myXML; //You can use the notation below to return an element that contains a particular //attribute and value. This is helpful if you have multiple elements with the same //name and different attribute values and you already know the attribute //and value you need xml.XPath = "/root/parent/child[@attr1='1']"; Console.WriteLine(xml.XText); //outputs child1 //You may also specify the i-th sub element with the given name xml.XPath = "/root/parent/child[2]"; Console.WriteLine(xml.XText); //outputs child2 //Or you can specify the just the i-th sub element xml.XPath = "/root/parent/[2]"; Console.WriteLine(xml.XText); //outputs child2

We appreciate your feedback.  If you have any questions, comments, or suggestions about this article please contact our support team at kb@nsoftware.com.