Thursday, March 6, 2008

misunderstand when using XmlNode.SelectSingleNode function

Keywords: System.Xml, XmlNode, XPath


在使用System.Xml命名空间的XmlNode类, 有一个方法 XmlNode.SelectSingleNode(string xpath).


刚开始使用它时, 对它的作用理解有误. 如果XPath以"/"开始, 其意义为从根节点开始搜索Node. 原本想使用XmlNode456对象的SelectSingleNode(XPath123)方法, XPath123这个表达式所指的根节点应是XmlNode456, 但事实是, 这个函数仍以XmlNode456所在文档的根节点root作为搜索的起点.


要搜索Node456下的Child节点, 有2个方法, 最好使用方法2, 因为它更加简单.


方法1: 如果想通过SelectSingleNode()来搜索的话, 构建一个从根节点root指向Child的绝对路径的XPath, (XPath表达式应该以"./"开头)


方法2: 将Node456.OutXml赋值给一个tempXmlDocument., 然后再使用tempXmlDocument.SelectSingleNode(AbsoluteXPath), 可以定位到子节点. 这时候, 你可以用tempXmlDocument来直接提取Node456节点的内容, 如果还要修改Node456, 应该在修改tempXmlDocument之后, 再将修改后的内容保存到原有的Node456节点上.




XmlDocument tempXmlDocument = new XmlDocument();
//Load the xml from Node456
tempXmlDocument.LoadXml(Node456.OutXml);

//extract Info from tempXmlDocument
//...


//change the tempXmlDocument info
//...

//save the result after changed into the Node456
Node456.InnerXml = tempXmlDocument.DocumentElement.InnerXml;

No comments: