How to get xpath from an XmlNode instance

后端 未结 14 1087
难免孤独
难免孤独 2020-11-30 18:17

Could someone supply some code that would get the xpath of a System.Xml.XmlNode instance?

Thanks!

14条回答
  •  庸人自扰
    2020-11-30 18:54

    I had to do this recently. Only elements needed to be considered. This is what I came up with:

        private string GetPath(XmlElement el)
        {
            List pathList = new List();
            XmlNode node = el;
            while (node is XmlElement)
            {
                pathList.Add(node.Name);
                node = node.ParentNode;
            }
            pathList.Reverse();
            string[] nodeNames = pathList.ToArray();
            return String.Join("/", nodeNames);
        }
    

提交回复
热议问题