This method updates an XML element with a new set of attributes. If the element is not found the XML is unchanged. The attributes keys and values must all be Strings. @param xml A stream of the XML data. @param elementName The name of the element to update. @param newAttrs The new attributes to pla
(
BufferedReader xml, String elementName, Map<String,String> newAttrs
)
| 510 | * @return A string of the whole XML source, with the element updated. |
| 511 | */ |
| 512 | public static String updateXmlElement( |
| 513 | BufferedReader xml, String elementName, Map<String,String> newAttrs |
| 514 | ) throws IOException { |
| 515 | String line = null; |
| 516 | String nl = Strings.getNl(); |
| 517 | StringBuffer newXml = new StringBuffer(); |
| 518 | |
| 519 | // read the whole source |
| 520 | while( ( line = xml.readLine() ) != null ) { |
| 521 | newXml.append(line); |
| 522 | newXml.append(nl); |
| 523 | } |
| 524 | |
| 525 | // find the location of the element |
| 526 | int start = newXml.toString().indexOf("<" + elementName); |
| 527 | if(start == -1) return newXml.toString(); |
| 528 | int end = newXml.toString().indexOf(">", start); |
| 529 | if(end == -1) return newXml.toString(); |
| 530 | |
| 531 | // check if the old element is empty (ends in "/>") or not |
| 532 | boolean isEmpty = false; |
| 533 | if(newXml.toString().charAt(end - 1) == '/') isEmpty = true; |
| 534 | |
| 535 | // create the new element string with the new attributes |
| 536 | StringBuffer newElement = new StringBuffer(); |
| 537 | newElement.append("<"); |
| 538 | newElement.append(elementName); |
| 539 | |
| 540 | // add in the new attributes |
| 541 | Iterator<Map.Entry<String,String>> iter = newAttrs.entrySet().iterator(); |
| 542 | while(iter.hasNext()) { |
| 543 | Map.Entry<String,String> entry = iter.next(); |
| 544 | String key = entry.getKey(); |
| 545 | String value = entry.getValue(); |
| 546 | |
| 547 | newElement.append(" "); |
| 548 | newElement.append(DocumentXmlUtils.combinedNormalisation(key)); |
| 549 | newElement.append("=\""); |
| 550 | newElement.append(DocumentXmlUtils.combinedNormalisation(value)); |
| 551 | newElement.append("\"" + nl); |
| 552 | } |
| 553 | |
| 554 | // terminate the element |
| 555 | if(isEmpty) newElement.append("/"); |
| 556 | newElement.append(">"); |
| 557 | |
| 558 | // replace the old string |
| 559 | newXml.replace(start, end + 1, newElement.toString()); |
| 560 | |
| 561 | return newXml.toString(); |
| 562 | } // updateXmlElement(Reader...) |
| 563 | |
| 564 | /** |
| 565 | * This method updates an XML element in an XML file |