I'm trying to create a new xml with a structure and at the same time add elements via this
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);
However .append doesn't seem to add anything and I end up with an empty file.
This approach is based on this SO answer but the "Document document = $(file).document();" line gives me an exception as the file doesn't exist - hence the use of DocumentBuilder.
Of course I realise that I can create new xml file through a host of other means I am trying to stick with Joox based approach at the moment.
Working version after feedback from Lucas Eder (Joox "all the way" option)
// Initial block to create xml structure
Match x = $("Data",
$("Styles",
$("Style",
$("Attributes", "")
).attr("name", styleName)
)
).attr("xmlns", "http://www.mycompany.com/data");
// example xpath into structure to add element attribues
// as required
Match xpath = x.xpath("//Attributes");
xpath = xpath.append($("Attribute", "").attr("key", styleKey));
x.write(file);
Produces the following:
<Data xmlns="http://www.mycompany.com/data">
<Styles>
<Style name="myStyle">
<Attributes>
<Attribute key="styleKeyValue"/>
</Attributes>
</Style>
</Styles>
</Data>