Xpath - How to get all attribute names and element values

I am using xpath in java. I want to get all the attributes (name and value) of an element. I found a query to get the attribute values ​​of an element, now I want to get the attribute names myself or the names and values ​​in one query.

<Element1 ID="a123" attr1="value1" attr2="value2" attr3="value3" attr4="value4" attr5="value5" /> 

Here, using the following query to get all attribute values Element1 XmlUtils.getAttributes(Path, String.format("//*/@*")); Using this format //*/@* , I can get the values. the result will be value1 value2 value3 value4 value5 a123

Now I want to know a query to get all attribute names or a query to get all attribute names and values.

+6
java xpath attributes elements
source share
2 answers

To select all attributes of all elements of a document Element1: //Element1/@* . This will return a node node containing attribute nodes. Then you can iterate over the node nodes.

If you already have a node context and want to find the results under it, the request will be .//Element1/@* . This is usually more efficient than querying the entire document.

 // input is an InputSource or a DOM node NodeList nl = (NodeList) xpath.evaluate("//Element1/@*", input, XPathConstants.NODESET); int length = nl.getLength(); for( int i=0; i<length; i++) { Attr attr = (Attr) nl.item(i); String name = attr.getName(); String value = attr.getValue(); } 

And it may be more efficient to find all the elements of a given name using getElementsByTagName .

 NodeList nl = document.getElementsByTagName("Element1"); 

To get the attributes of a specific element, iterate over its attribute properties.

 NamedNodeMap nl = element.getAttributes(); int length = nl.getLength(); for( int i=0; i<length; i++) { Attr attr = (Attr) nl.item(i); String name = attr.getName(); String value = attr.getValue(); } 
+23
source share

I had to do this on the Oracle Service Bus and I had to use only xPath to create the cache key, and the solution that worked for me was:

 concat( string-join(//*[string-length(normalize-space(string-join(text(), ''))) > 0]/concat(local-name(), ':', normalize-space(string-join(text(), ''))), '_'), '_', string-join(//@*[normalize-space(.) != '']/concat(name(), ':', .), '_') ) 
+2
source share

All Articles