我有以下XML文件:
<Tables>
<table>
<row></row>
</table>
<Tables>
而且我想将其编辑为:
<Tables>
<table>
<row>some value</row>
</table>
<Tables>
我使用文件编写器编写XML文件。我该如何编辑?
发现我创建了一个包含编辑内容的临时文件,然后删除了原始文件并重命名了该临时文件。还有其他方法吗?
这是我编写文件的代码:
public boolean createTable(String path, String name, String[] properties) throws IOException {
FileWriter writer = new FileWriter(path);
writer.write("<Tables>");
writer.write("\t<" + name + ">");
for(int i=0; i<properties.length; i++){
writer.write("\t\t<" + properties[0] + "></" + properties[0] + ">");
}
writer.write("\t</" + name + ">");
writer.write("</Tables>");
writer.close();
return false;
}
File file = new File("input.xml");
byte[] data;
try (FileInputStream fis = new FileInputStream(file)) {
data = new byte[(int) file.length()];
fis.read(data);
}
String input = new String(data, "UTF-8");
String tag = "<row>";
String newXML = input.substring(0, input.indexOf(tag) + tag.length()) + "your value" + input.substring(input.indexOf(tag) + tag.length(), input.length());
try (FileWriter fw = new FileWriter(file)) {
fw.write(newXML);
}
System.out.println("XML Updated");
DOM
XML以树形结构加载到内存中。SAX
XML被作为事件序列处理。这是一个推式解析器,其中解析器为每个事件调用您的代码。import com.github.underscore.lodash.U;
public class MyClass {
public static void main(String args[]) {
String xml = "<Tables>"
+ " <table>"
+ " <row></row>"
+ " </table>"
+ "</Tables>";
java.util.Map<String, Object> object = (java.util.Map<String, Object>) U.fromXml(xml);
U.set(object, "Tables.table.row", "some value");
System.out.println(U.toXml(object));
}
}
// <Tables>
// <table>
// <row>some value</row>
// </table>
//</Tables>