I woul...">

XPath / XQuery: select the root node with your attributes without childs

I have xml:

<Customer id=""> <Name /> <Address /> </Customer> 

I would like to select ONLY the root node with its attributes without its child nodes:

 <Customer id=""/ > 

Is this possible with XPath?

+4
source share
4 answers

No, this is not possible in XPath.

You cannot select a node without its children, because without its children it will be different from node, so you would not select node from the source document.

To create the output you need, you need to use a language that allows you to create new nodes, so you cannot do this in XPath. You can use XQuery to create new nodes, this should work:

 element {fn:node-name(/*)} {/*/@*} 
+2
source

XPath does not modify any source XML document, and this is by design .

To create a new XML document from an existing one, a conversion is required.

XSLT was specifically designed to convert a set of trees (including XML documents) into result trees.

This conversion is :

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes"/> <xsl:template match="/*"> <xsl:copy> <xsl:copy-of select="@*"/> </xsl:copy> </xsl:template> </xsl:stylesheet> 

when applied to the provided XML document :

 <Customer id=""> <Name /> <Address /> </Customer> 

creates the desired, correct result :

 <Customer id=""/> 
+2
source
 $doc = new DOMDocument(); $doc->loadHTML($str); $xPath = new DOMXpath($doc); $xPathQuery = "//text()[contains(translate(.,'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'), '<Customer id=\"\">')]"; $elements = $xPath->query($xPathQuery); if($elements->length > 0){ foreach($elements as $element){ print "Found: " .$element->nodeValue."<br />"; } 
0
source

This is an XQuery expression:

 element {name(/*)} {/*/@*} 

Conclusion:

 <?xml version="1.0" encoding="UTF-8"?><Customer id=""/> 
0
source

All Articles