我正在尝试创建一个具有结构的新 xml,同时通过它添加元素
String styleName = "myStyle";
String styleKey = "styleKeyValue";
File file = new File("test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.newDocument();
Match x = $(document)
.namespace("s", "http://www.mycompany.com/data")
.append(
$("Data",
$("Styles",
$("Style",
$("Attributes", "")
).attr("name", styleName)
)
)
);
Match xpath = x.xpath("//s:Attributes");
xpath = xpath.append($("Attribute", "").attr("key", styleKey));
x.write(file);
但是 .append 似乎没有添加任何内容,我最终得到一个空文件。
这种方法基于这个 SO 答案,但是“Document document = $(file).document();” 行给了我一个例外,因为该文件不存在 - 因此使用 DocumentBuilder.
当然,我意识到我可以通过许多其他方式创建新的 xml 文件,我目前正在尝试坚持基于 Joox 的方法。