我有一个XML文件,我打开并编辑节点中的几个属性,然后将其保存回来,但由于某种原因,保存的XML没有像以前那样正确缩进。
下面是我保存XML文件的代码: 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);
虽然我指定了
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
XML没有正确缩进,我想让XML处于以前的状态(除了所做的更改)
任何帮助都将是非常感激的。
您需要启用'INDENT'并设置变压器的缩进量:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
看看这是否有效。
VTD-XML是一个Java库,可以修改XML文件的部分内容,同时保留空白格式。
下面的代码使用XPath在XML文件中选择某些属性。代码修改所选属性的值,然后将结果写入输出文件。
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();
}
}
}