Reputation:
I've some tags in a word file which looks like <tag>
.
Now I get the content of the Word file with docx4j and loop through every line and search for this tag. When I find one, then i replace it with a String. But this code i tried doesn't work and now i really don't know how i can realise it!
Here's the code i've already tried:
WordprocessingMLPackage wpml = WordprocessingMLPackage.load(new File(path));
MainDocumentPart mdp = wpml.getMainDocumentPart();
List<Object> content = mdp.getContent();
String line;
for (Object object : content) {
line = object.toString();
if (line.contains("<tag>")) {
line.replace("<tag>", "<newTag>");
}
}
Any tips or solutions how i can achieve it?
Upvotes: 1
Views: 853
Reputation: 10151
String (line) is immutable, therefore replace("<tag>", "<newTag>")
does not modify your line
it creates a new modified one.
Your code shoudl do something like this:
for (Object object : content) {
line = object.toString();
if (line.contains("<tag>")) {
line= line.replaceAll("<tag>", "<newTag>");
}
writeLineToNewFile(line);
}
or shorter:
for (Object object : content) {
writeLineToNewFile(object.toString().replace("<tag>", "<newTag>");
}
Upvotes: 0
Reputation: 15863
The things in your List will be org.docx4j.wml.P (paragraphs), or Tbl (tables) or other block level content.
Paragraphs contain runs, which in turn contain the actual text.
For the suggested way of doing what you want to do, see the VariableReplace sample.
Better yet, consider content control data binding.
Otherwise, if you want to roll your own approach, see the Getting Started guide for how to traverse, or use JAXB-level XPath.
Upvotes: 1
Reputation: 8928
One of your problems is that you modify String line
which has no effect on anything. line.replace("<tag>", "<newTag>");
result of this operation is ignored. you would definitely want to do sth with that, right?
Also, if object
in your loop is not an instaneOf String
, then line
and object
are pointing to different objects.
You need to modify contents but not the way you're doing this. Please read getting started
Also there are lots of examples (sample code) in source code download section
If you have any concrete problems after reading the getting started, we'll be happy to help you.
Upvotes: 1
Reputation: 438
First you should use replaceAll()
instead of replace()
.
Then you should store this String into an object you can serialize back after modification to the Word file.
Furthermore I think that it would also be good to handle closing tags (if there some) ...
Upvotes: 0