XPath of Node

Inhaltsverzeichnis
Zuletzt aktualisiert
by Anonym (13 Aug)
Re: XPath of Node (Software Development)

How to get an XPath from an XML-Node? Is there something like node.getXPath()?

Answer: http://lekkimworld.com/2007/06/19/building_xpath_expression_from_xml_node.html

  • Java:
    import java.util.Stack;
    
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    
    /**
     * Utility class for dealing with XML DOM elements.
     * 
     * 
     * @author Mikkel Heisterberg, lekkim@lsdoc.org
     */
    public class ElementUtil {
       
       /**
        * Constructs a XPath query to the supplied node.
        * 
        * @param n
        * @return
        */
       public static String getXPath(Node n) {
          // abort early
          if (null == n) return null;
    
          // declarations
          Node parent = null;
          Stack hierarchy = new Stack();
          StringBuffer buffer = new StringBuffer();
    
          // push element on stack
          hierarchy.push(n);
    
          parent = n.getParentNode();
          while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) {
             // push on stack
             hierarchy.push(parent);
    
             // get parent of parent
             parent = parent.getParentNode();
          }
    
          // construct xpath
          Object obj = null;
          while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) {
             Node node = (Node) obj;
             boolean handled = false;
    
             // only consider elements
             if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element e = (Element) node;
    
                // is this the root element?
                if (buffer.length() == 0) {
                   // root element - simply append element name
                   buffer.append(node.getLocalName());
                } else {
                   // child element - append slash and element name
                   buffer.append("/");
                   buffer.append(node.getLocalName());
                   
                   if (node.hasAttributes()) {
                      // see if the element has a name or id attribute
                      if (e.hasAttribute("id")) {
                         // id attribute found - use that
                         buffer.append("[@id='" + e.getAttribute("id") + "']");
                         handled = true;
                      } else if (e.hasAttribute("name")) {
                         // name attribute found - use that
                         buffer.append("[@name='" + e.getAttribute("name") + "']");
                         handled = true;
                      }
                   }
    
                   if (!handled) {
                      // no known attribute we could use - get sibling index
                      int prev_siblings = 1;
                      Node prev_sibling = node.getPreviousSibling();
                      while (null != prev_sibling) {
                         if (prev_sibling.getNodeType() == node.getNodeType()) {
                            if (prev_sibling.getLocalName().equalsIgnoreCase(node.getLocalName())) {
                               prev_siblings++;
                            }
                         }
                         prev_sibling = prev_sibling.getPreviousSibling();
                      }
                      buffer.append("[" + prev_siblings + "]");
                   }
                }
             }
          }
    
          // return buffer
          return buffer.toString();
       }
    }
    
  • Java-Script:
    function GetXPath(GivenNode)
    {
     
     if (null == GivenNode) return null
     
     // declarations -----------------------------------------------
     var TempParent = null
     var Hierarchy = new Array()
     var StringBuffer = ""
     //-------------------------------------------------------------
     
     // push first element on stack
     Hierarchy.push(GivenNode)
     
     // search for all ancestors -----------------------------------
     var TempParent = GivenNode.parentNode
     var TempNode
     var TempSibling
     var PrevSiblings
     var Handled = false
     while (null != TempParent && TempParent.nodeType != Node.DOCUMENT_NODE)
     {
      Hierarchy.push(TempParent)
      TempParent = TempParent.parentNode
     }
     //-------------------------------------------------------------
    
     // construct xpath
     while (!(Hierarchy.length == 0) && null != (TempNode = Hierarchy.pop()))
     {
      Handled = false
      // only consider elements
      if (TempNode.nodeType == Node.ELEMENT_NODE)
      {
                // is this the root element?
       if (StringBuffer.length == 0)
       {
        // root element - simply append element name
        StringBuffer = StringBuffer + TempNode.localName
                }
                else
                {
                 // child element - append slash and element name
                 StringBuffer = StringBuffer + "/" + TempNode.localName
                 if (TempNode.hasAttributes())
                 {
                  // see if the element has a name or id attribute
                  if (TempNode.attributes.getNamedItem("id"))
                  {
                   StringBuffer = StringBuffer + "[@id='" + TempNode.attributes.getNamedItem("id").nodeValue + "']"
                   Handled = true
                  }
                  else if (TempNode.attributes.getNamedItem("name"))
                  {
                   StringBuffer = StringBuffer + "[@name='" + TempNode.attributes.getNamedItem("name").nodeValue + "']"
                   Handled = true
                  }
                 }
                 
                 if (!Handled)
                 {
                  // no known attribute we could use - get sibling index
                  PrevSiblings = 1
                  TempSibling = TempNode.previousSibling
                  while (null != TempSibling)
                  {
                   if (TempSibling.nodeType == TempNode.nodeType)
                   {
                    if (TempSibling.localName.toLowerCase() == TempNode.localName.toLowerCase())
                    {
                     PrevSiblings++
                    }
                   }
                   TempSibling = TempSibling.previousSibling
                  }
                  StringBuffer = StringBuffer + "[" + PrevSiblings + "]"
                 }
                }
      }
     }
     // return buffer
     return StringBuffer
    }
    

Stichwörter:

Geben Sie Stichwörter ein, die dieser Seite hinzugefügt werden sollen:
Wait Image 
Sie suchen ein Stichwort? Beginnen Sie einfach zu schreiben.
  1. 13. Aug

    Anonym sagt:

    The code works fine, but I must change the Method node.getLocalName() in node.ge...

    The code works fine, but I must change the Method node.getLocalName() in node.getNodeName() thx!

Kommentar hinzufügen