find xml xpath code example

Example: c# xml node get xpath

public List<string> RetrieveXmlLeafFieldPath(XmlDocument generateEmptyPdfTemplate)
{
  XmlNodeList xmlNodeList = generateEmptyPdfTemplate.SelectNodes("//*");
  if (xmlNodeList==null) return new List<string>();
  var result = xmlNodeList.Cast<XmlNode>().
    Where(xmlNode => xmlNode.LastChild.NodeType == XmlNodeType.Text).
    Select(xmlNode=> 
           FindXPath(xmlNode)
          ).ToList();
  return result;
}

private string FindXPath(XmlNode node)
{
  StringBuilder builder = new StringBuilder();
  while (node != null)
  {
    switch (node.NodeType)
    {
      case XmlNodeType.Attribute:
        builder.Insert(0, "/@" + node.Name);
        node = ((XmlAttribute)node).OwnerElement;
        break;
      case XmlNodeType.Element:
        int index = FindElementIndex((XmlElement)node);
        //for <sequence> type builder.Insert(0, "/" + node.Name + "[" + index + "]");
        builder.Insert(0, "/" + node.Name );
        node = node.ParentNode;
        break;
      case XmlNodeType.Document:
        return builder.ToString();
      default:
        throw new ArgumentException("Only elements and attributes are supported");
    }
  }
  throw new ArgumentException("Node was not in a document");
}

static int FindElementIndex(XmlElement element)
{
  XmlNode parentNode = element.ParentNode;
  if (parentNode is XmlDocument)
  {
    return 1;
  }
  XmlElement parent = (XmlElement)parentNode;
  int index = 1;
  foreach (XmlNode candidate in parent.ChildNodes)
  {
    if (candidate is XmlElement && candidate.Name == element.Name)
    {
      if (candidate == element)
      {
        return index;
      }
      index++;
    }
  }
  throw new ArgumentException("Couldn't find element within parent");
}