Convenient utility to build XML models by evaluating XPath expressions.
Include an artifact with necessary model extension into your project:
<dependency>
<groupId>com.github.simy4.xpath</groupId>
<artifactId>xpath-to-xml-dom</artifactId>
<version>2.2.0</version>
</dependency>Now having an XML structure i.e.:
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
</breakfast_menu>and one of supported models:
importjava.io.StringReader;
importjavax.xml.parsers.*;
importorg.xml.sax.InputSource;
classExample0 {
privatestaticfinalStringxmlSource = "my-xml-source";
publicstaticDocumentdocument(Stringxml) throwsException {
vardocumentBuilderFactory = DocumentBuilderFactory.newInstance();
vardocumentBuilder = documentBuilderFactory.newDocumentBuilder();
varinputSource = newInputSource(newStringReader(xml));
returndocumentBuilder.parse(inputSource);
}
}you can:
- alter existing paths
importcom.github.simy4.xpath.XmlBuilder;
classExample1extendsExample0 { publicstaticvoidmain(String... args) throwsException {
newXmlBuilder()
.put("/breakfast_menu/food[1]/price", "$7.95")
.build(document(xmlSource));
}
}- append new elements
importcom.github.simy4.xpath.XmlBuilder;
classExample2extendsExample0 { publicstaticvoidmain(String... args) throwsException {
newXmlBuilder()
.put("/breakfast_menu/food[name='Homestyle Breakfast'][price='$6.95'][description='Two eggs, bacon or sausage, toast, and our ever-popular hash browns']/calories", "950")
.build(document(xmlSource));
}
}- remove paths
importcom.github.simy4.xpath.XmlBuilder;
classExample3extendsExample0 { publicstaticvoidmain(String... args) throwsException {
newXmlBuilder()
.remove("/breakfast_menu/food[name='Belgian Waffles']")
.build(document(xmlSource));
}
}- combine any of the above actions into a single modification action
importcom.github.simy4.xpath.XmlBuilder;
classExample4extendsExample0 { publicstaticvoidmain(String... args) throwsException {
newXmlBuilder()
.remove("/breakfast_menu/food[name='Homestyle Breakfast']")
.put("/breakfast_menu/food[name='Homestyle Breakfast'][price='$6.95'][description='Two eggs, bacon or sausage, toast, and our ever-popular hash browns']/calories", "950")
.build(document(xmlSource));
}
}