Reputation: 307
I have an XML file that I open and edit few attributes in the node and then save it back, but due to some reason whatsoever the saved XML's are not indented properly as the one before.
Here my code through which I save the XML file:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(Path));
transformer.transform(source, result);
Although I have specified
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
the XML is not indented properly, I would like to have the XML in the state as it was before (except the changes that were made)
Any help will be really appreciated.
Thanks a lot in advance.
Upvotes: 5
Views: 823
Reputation: 7041
VTD-XML is a Java library that modifies parts of an XML file while preserving whitespace formatting.
Below is code that uses XPath to select certain attributes in an XML file. The code modifies the values of the selected attributes and then writes the results to an output file.
import com.ximpleware.AutoPilot;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.TranscodeException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class TransformFile
{
public static void main(String[] args)
throws IOException, XPathParseException, ModifyException, NavException,
XPathEvalException, TranscodeException
{
String inFilename = "input.xml";
String outFilename = "output.xml";
transform(inFilename, outFilename);
}
public static void transform(String inXmlFilePath, String outXmlFilePath)
throws XPathParseException, ModifyException, XPathEvalException,
NavException, IOException, TranscodeException
{
String xpath =
"//Configuration[starts-with(@Name, 'Release')]/Tool[@Name = 'VCCLCompilerTool']/@BrowseInformation[. = '0']";
OutputStream fos = new FileOutputStream(outXmlFilePath);
try {
VTDGen vg = new VTDGen();
vg.parseFile(inXmlFilePath, false);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath(xpath);
XMLModifier xm = new XMLModifier(vn);
int attrNodeIndex;
while ((attrNodeIndex = ap.evalXPath()) != -1) {
// An attribute value node always immediately follows an
// attribute node.
int attrValIndex = attrNodeIndex + 1;
xm.updateToken(attrValIndex, "1");
}
xm.output(fos);
}
finally {
fos.close();
}
}
}
Upvotes: 1
Reputation: 2238
You need to enable 'INDENT' and set the indent amount for the transformer:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
See if this works.
Upvotes: 1