| |
|
| |
How to Find XML NodesExplains how to find data in an XML tree. There appear to be a million ways to do this in .NET. Here are some ways to fit various situations.XML ReaderThe XMLReader class is good for navigating simple nodes in order.Sample tree: <Config configured="3" IPAddress="192.168.1.1"></Config >Sample code using XMLReader:
public void Unpack(string dataString)
{
// Convert from string to data stream, which is what the reader expects.
byte[] bytes = Encoding.UTF8.GetBytes(dataString);
MemoryStream memStream = new MemoryStream(bytes);
XmlReader reader = XmlReader.Create(memStream);
// Go through the XML until we reach the the expected elements
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Config")
{
// Process the attributes
while (reader.MoveToNextAttribute())
{
switch (reader.Name)
{
case "configured":
m_isConfigured = bool.Parse(reader.Value);
break;
case "IPAddress":
m_IPAddress = IPAddress.Parse(reader.Value);
break;
}
}
}
}
}
XPathThe XPath class is good when you want to look up nested nodes, or jump around in the XML without necessarily parsing everything in order.Sample tree:
<locale>
<phrases>
<phrase name="PH_HELLO">Hello</phrase>
<phrase name="PH_GOODBYE">Goodbye</phrase>
...
</phrases>
</locale>
Sample code (using XPath):
public string GetPhrase(string name)
{
XMLDocument resourceFile = new XMLDocument;
resourceFile.Load("C:/phrases.xml");
// Use the XPath utils to navigate to:
//
| |
|
All content copyright 1996-2008 by Linda Naughton O'Meara unless otherwise noted.
Shadowrun is a copyright and trademark of WizKids, LLC.
Earthdawn is a copyright and trademark of FASA Corporation.
Crimson Skies is a copyright and trademark of Microsoft Corporation.
Babylon 5 is a copyright and trademark of Time Warner Entertainment.
Battlestar Galactica is a copyright of Sci Fi / Universal.
Any use of characters, names, places, etc. from these systems is done with the greatest respect for their creators, and is not intended as a challenge to any copyrights or trademarks.
| |