• 0

[Java] How to get all XML attributes that end with "Key"


Question

Hi all,

I'm writing a Java program to read all XML files in a folder and find all the attributes in those files that end with "Key" and their parent element. For example:

<Element1 FileKey="123">

<Element11 File2Key="456" />

</Element1>

I want returned something like:

Element1=FileKey

Element11=File2Key

I can loop through the files and have each file saved as a Document, but I'm having a hard time getting the results. Here's what I have now for code:

for(int n = 0; n &lt; xmlFiles.length; n++) {
					TraceLogger.logTrace("Processing file: " + xmlFiles[n].getName(), TraceLogger.info);
					try {
						Document xmlDocument = getDocumentFromFile(xmlFiles[n].getAbsolutePath());

						XPathFactory xPathFactory = XPathFactory.newInstance();
						XPath xPath = xPathFactory.newXPath();
						String xPathString = "//*[contains(local-name(@*), 'Key')]";		// Any attributes with *Key
						XPathExpression xPathExpression = xPath.compile(xPathString);
						Object result = xPathExpression.evaluate(xmlDocument, XPathConstants.STRING);
						keyAttributes.add(result);
						TraceLogger.logTrace("Result: " + result);
					}
					catch(Exception ex) {
						ex.printStackTrace();
					}	 							
}

But the Result is empty. I'm thinking my Xpath is wrong but I'm not sure what exactly it should be. Does anyone know how to obtain the information I want?

Thanks for any help. :)

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.