Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Edit XML file and Update Values in Java
// Edit XML file by updating values using Java
Editor editor = new Editor("path/XMLData.xml");
// Create XML editing options
XmlEditOptions editOptions = new XmlEditOptions();
editOptions.setAttributeValuesQuoteType(QuoteType.DoubleQuote);
editOptions.setRecognizeEmails(true);
editOptions.setRecognizeUris(true);
editOptions.setTrimTrailingWhitespaces(true);
// Prepare and Edit the Editable Document
EditableDocument beforeEdit = editor.edit(editOptions);
// Edit XML
String originalTextContent = beforeEdit.getContent();
String updatedTextContent = originalTextContent.replace("John", "Samuel");
List<IHtmlResource> allResources = beforeEdit.getAllResources();
// Create new EditableDocument with updated content
EditableDocument afterEdit = EditableDocument.fromMarkup(updatedTextContent, allResources);
// Create WordProcessing save options
WordProcessingSaveOptions wordSaveOptions = new WordProcessingSaveOptions(WordProcessingFormats.Docx);
// Create TXT save options
TextSaveOptions txtSaveOptions = new TextSaveOptions();
txtSaveOptions.setEncoding(StandardCharsets.UTF_8);
// Save edited XML data in DOCX and TXT format
editor.save(afterEdit, "path/updated-xml-data.docx", wordSaveOptions);
editor.save(afterEdit, "path/updated-xml-data.txt", txtSaveOptions);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment