In C# code-behind, you'd do something like:
Code:
// Build a doc
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
doc.DocumentElement.AppendChild(root);
XmlElement node = doc.CreateElement("Node1");
node.InnerText = "foo";
root.AppendChild(node);
node = doc.CreateElement("Node2");
node.InnerText = "bar";
root.AppendChild(node);
// To get the value of node2
XmlElement nodeget = doc.SelectSingleNode("root/Node2/text()");
if (null != node) {
String nodevalue = nodeget.Value;
}
Note a couple of differences between the C# version and the ASP version:
1) In my XPath query, I used the text() function. According to the W3C spec, the text of a node isn't actually stored in the node, but in another node below it that is of type "textnode". This function gets you this value.
2) I checked the nodeget object to see if the SelectSingleNode method actually returned anything. If your XML has been validated against a XSD, and you're 100% sure the node is present, you can skip this step. If some 3rd party is sending you the XML, or it hasn't been validated, then you need to test to see if the XPath actually gave you something.
3) I'm using the .Value property to extract the value of the node, rather than the InnerText property. Under .NET, the InnerText docs say that it gives you: "The concatenated values of the node and all its children.", which may not be what you want (and likely isn't).
4) When creating my doc from XmlElement objects, I used the InnerText property. Basically because I'm lazy, and also because I know there are no children nodes to get overwritten.
And note that this code will be easy to move to VB.NET if needed, as most of it is framework calls. Big differences would be removing the semi-colon line separators, and changing how the variables are declared.
Hope this helps.
Chip H.
If you want to get the best response to a question, please check out FAQ222-2244 first