-
New to XML
I am new to working with XML, and I am having trouble wrapping my head around one of the concepts. I have an xml file formatted as follows:
<List>
<Item>
<Stat1>Blah</Stat1>
<Stat2>Blah</Stat2>
<Stat3>Blah</Stat3>
</Item>
<Item>
<Stat1>Blah</Stat1>
<Stat2>Blah</Stat2>
<Stat3>Blah</Stat3>
</Item>
<Item>
<Stat1>Blah</Stat1>
<Stat2>Blah</Stat2>
<Stat3>Blah</Stat3>
</Item>
</List>
I need to be able to search for a particular item based upon it's value for Stat1, and then I need to be able to retrieve Stat2 and Stat3 for that item. I know that I can load them all into a node list and select all nodes matching my search criteria, but I am unsure how to proceed from there (assuming that is the right way to begin). Any help would be appreciated.
-
Re: New to XML
I'm pretty sure you can do this using XPath but here is a possible solution using code. You would need to tweak this depending on your xml string and how you actually want to use the data but this could get you started.
Note that loading the xml into the XmlDocument could possible cause a performance hit depending on how big your xml gets.
Code:
XmlDocument doc = new XmlDocument();
doc.loadXml(myXml);
//Only if List is the Root node.
XmlNode listNode = doc.DocumentElement;
string stat2 = "";
string stat3 = "";
foreach(XmlNode itemNode in listNode.SelectNodes("Item"))
{
XmlNode stat1Node = itemNode.SelectSingleNode("Stat1");
if (stat1Node.InnerText == "MyValue")
{
XmlNode stat2Node = itemNode.SelectSingleNode("Stat2");
stat2 = stat2Node.InnerText;
XmlNode stat3Node = itemNode.SelectSingleNode("Stat3");
stat3 = stat3Node.InnerText;
//get out of the foreach loop
break;
}
}
if (stat2 != "" && stat3 != "")
{
//Do something with the values
}
Let me know if I'm an idiot and doing this all wrong or even let me know if this is a good solution.
-
Re: New to XML
That worked perfectly. The xml file will never contain more than a few dozen items, so I don't think that there will be performance problems by loading it into the XmlDocument. Thanks for the help!
-
Re: New to XML
Search for Item with Stat1='4a'.
Code:
XmlDocument xmlDoc;
XmlNode xmlStatOneNode;
String sFileName = @"c:\test2.xml";
xmlDoc = new XmlDocument();
xmlDoc.Load(sFileName);
xmlStatOneNode = xmlDoc.SelectSingleNode("//List//Item[Stat1= '4a']");
if (xmlStatOneNode != null)
MessageBox.Show("Stat2=" + xmlStatOneNode.SelectSingleNode("Stat2").InnerText +
"\n" + "Stat3=" + xmlStatOneNode.SelectSingleNode("Stat3").InnerText);