How do we select all blingy wheels with a 5 bolt pattern using a XPath Statement?
(*Without linq*)
<Car>
<Wheel brand="HRE" boltPattern="5" Bling="True"></Wheel>
<Wheel brand="stockHonda" boltPattern="4" Bling="False"></Wheel>
<Wheel name="MOMO" boltPattern="4" Bling="True"></Wheel>
<Wheel name="SomeCrapRim" boltPattern="5" Bling="false"></Wheel>
</Car>
Answer:
Select( xmlString, new string[] { "Cars/Wheel[@boltPattern='5']", "node()/Wheel[@Bling='True']"});
Note: This is not optimized code, it is example code. There is no need to load up the document over and over.
public static string Select(string xmlSource, string[] xPaths)
{
string xmlresult = xmlSource;
for (int i = 0; i < xPaths.Length; i++)
{
xmlresult = Select(xmlresult, xPaths[i]);
}
return xmlresult;
}
public static string Select(string xmlSource, string xPath)
{
if (xmlSource.Length == 0)
{
return String.Empty;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlSource);
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator iter1 = nav.Select(xPath);
if (iter1.Count == 0)
{
return String.Empty;
}
StringBuilder xml = new StringBuilder();
xml.Append("<root>");
while (iter1.MoveNext())
{
xml.Append(iter1.Current.OuterXml);
xml.Append("\r\n");
}
xml.Append("</root>");
return xml.ToString();
}