XML - InsertSingleNode?

It's easy to get data out from an XML doc given a path (doc.SelectSingleNode(@"/customer/address/zip"), but what about building an XML doc bit by bit? What about InsertSingleNode? There are plenty of times where programatically building an XML doc at the object level doesn't make sense or isn't possible, and plenty of cases where there isn't an object to be serialized (say, on projects I'm stepping into late in the game, or where the XML document format is dynamic).

Here's a simple method I used to add a value to an XML doc by a path. This doesn't support XPath syntax (beyond the simple “/” delimited node hierarchy). Is there a better way?

1:     public void InsertSingleNode(string strValue, ref XmlDocument doc, string strXmlPath)

2: {
3: string[] str = strXmlPath.Split(new char[] {'/'});
4:
5: XmlNode node=doc.SelectSingleNode(str[0]);
6: if (node==null)
7: node=doc.AppendChild(doc.CreateElement(str[0]));
8:
9: for(int level = str.GetLowerBound(0); level <= str.GetUpperBound(0); level++)
10: {
11: XmlNode sub=node.SelectSingleNode(str[level]);
12: if (sub==null && level!=0)
13: sub=node.AppendChild(doc.CreateElement(str[level]));
14: else
15: if(level==0)
16: sub=node;
17:
18: if(level==str.GetUpperBound(0))
19: sub.InnerText= strValue;
20: else
21: node = sub;
22: }
23: }


1 Comment

Comments have been disabled for this content.