0

I am trying to find the NodeList of the nodes containing any number of certain attributes in the XML file.

I can do the following and get the NodeList

DocumentBuilderFactory dbf  = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document schDoc = db.newDocument();
InputStream schStream = new ByteArrayInputStream(sch.xml);
schDoc = db.parse(schStream)
schDoc.getDocumentElement().normalize();

XPath xpath1 = XPathFactory.newInstance().newXpath();

String expAttStr = "descendant-or-self::*[contains(@Name,'total_amt')]";
XPathExpression exprForTotalAmt = xpath1.compile(expAttStr);
NodeList totalAmtNodeList = (NodeList) exprForTotalAmt.evaluate(schDoc,XPathConstants.NODESET);

This is good.. But how can I loop and change the value of the attribute name. I tried the following and didn't work:

List<String> listOfItems= Arrays.asList("total_amt", "purchase_amt", "sales_amt");
long count = listOfItems.stream.distinct().count();

for(int i = 0; i<count; i++){
String expAttStr = "descendant-or-self::*[contains(@Name,listOfItems.get(i)]";
XPathExpression exprForTotalAmt = xpath1.compile(expAttStr);
NodeList totalAmtNodeList = (NodeList) exprForTotalAmt.evaluate(schDoc,XPathConstants.NODESET);
//some tasks
}

Would really appreciate it if anyone can point me in the right direction. Thanks.

404or505
  • 165
  • 2
  • 3
  • 12
  • To iterate over the items in a list, consider using `for (String item : listOfItems)` - or other approaches [described here](https://stackoverflow.com/questions/18410035/ways-to-iterate-over-a-list-in-java). – andrewJames Aug 23 '20 at 14:11
  • 1
    To build your `expAttStr` using an item from your list, you need to concatenate the separate parts of your string to build the final string you need - there are [various ways to do this](https://stackoverflow.com/questions/53214160/java-best-practices-on-string-concatenation-and-variable-substituittion-in-stri) in Java. – andrewJames Aug 23 '20 at 14:32
  • Thank you, I guess string concatenation is the only way to change the values in this scenario. – 404or505 Aug 25 '20 at 01:34

0 Answers0