### XML Structure Example
Source: https://xmlbeam.org/projections
This snippet shows a simple XML structure that can be accessed using XMLBeam projections. It serves as the data source for the projection examples.
```xml
bar
```
--------------------------------
### Create XML Document from Scratch with Evaluation API (Java)
Source: https://xmlbeam.org/evaluationapi
This code example illustrates how to create an XML document from scratch using XMLBeam's Evaluation API. It involves initializing an empty map, populating it with data at specified paths, and then writing this structure to an XML file. This is useful for generating XML based on dynamic data. Dependencies include the XMLBeam library.
```java
XBProjector projector = new XBProjector();
//Create document from scratch
Map doc = projector.autoMapEmptyDocument(Object.class);
doc.put("/path/to/value", "value");
doc.put("/path/to/floatValue", 15.0f);
projector.io().file("example.xml").write(doc);
```
--------------------------------
### Java XML3D Projector Server and Geometry Example
Source: https://xmlbeam.org/t12
This Java code defines data structures for 3D geometry (Triplet, Vector, Vertex, Triangle) and includes a main method that acts as an HTTP server. It generates XML3D content, serves it to clients, and demonstrates mesh manipulation.
```java
public class RunExample {
public static class Triplet {
public T a, b, c;
public Triplet(T a, T b, T c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public String toString() {
return a + " " + b + " " + c;
}
}
public static class Vector extends Triplet {
public Vector(Float a, Float b, Float c) {
super(a, b, c);
}
}
public static class Vertex extends Triplet {
public Vertex(Vector a, Vector b, Vector c) {
super(a, b, c);
}
}
public static class Triangle extends Triplet {
public Triangle(Vertex a, Vertex b, Vertex c) {
super(a, b, c);
}
}
private static Vertex middle(Vertex a, Vertex b) {
Vector position = new Vector((a.a.a + b.a.a) / 2, (a.a.b + b.a.b) / 2, (a.a.c + b.a.c) / 2);
return new Vertex(position, new Vector(0f, 0f, 1f), null);
}
private static void addVertex(Xml3d mesh, Vertex v) {
int newIndex = 0;
String oldIndexes = mesh.getIndexes();
if (!oldIndexes.isEmpty()) {
List indexes = new ArrayList(Arrays.asList(oldIndexes.split(" ")));
newIndex = Integer.parseInt(indexes.get(indexes.size() - 1)) + 1;
}
String newIndexes = oldIndexes + (oldIndexes.endsWith(" ") ? "" : " ") + newIndex;
mesh.setIndexes(newIndexes);
String oldPositions = mesh.getPositions();
String newPositions = oldPositions + " " + v.a;
mesh.setPositions(newPositions);
String oldNormals = mesh.getNormals();
String newNormals = oldNormals + " " + v.b;
mesh.setNormals(newNormals);
}
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(8088);
if(Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(new URI("http://127.0.0.1:8088"));
}
while (true) {
Socket s = ss.accept();
XBProjector projector = new XBProjector(Flags.TO_STRING_RENDERS_XML);
projector.config().as(DefaultXMLFactoriesConfig.class).setOmitXMLDeclaration(false);
projector.config().as(DefaultXMLFactoriesConfig.class).setNamespacePhilosophy(NamespacePhilosophy.NIHILISTIC);
Xml3d xml3d = projector.io().fromURLAnnotation(Xml3d.class);
Vector normal = new Vector(0f, 0f, 1f);
for (float f = -2f; f <= 2f; f += 1f) {
Triangle t1 = new Triangle(new Vertex(new Vector(-1f, -1f, f), normal, null), new Vertex(new Vector(1f, -1f, f), normal, null), new Vertex(new Vector(0f, 1f, f), normal, null));
spanTriangles(xml3d, t1, 2+(int)f);
}
String page = xml3d.toString();
String header = "HTTP/1.0 200 OK\r\nContent-Type: application/xhtml+xml\r\nContent-Length: " + page.getBytes("UTF-8").length + "\r\n\r\n";
s.getOutputStream().write((header + page).getBytes("UTF-8"));
s.getOutputStream().flush();
Thread.sleep(1000);
s.close();
}
}
private static void spanTriangles(Xml3d xml3d, Triangle t, int i) {
if (i == 0) {
addTriangle(xml3d, t);
return;
}
Vertex ac = middle(t.a, t.c);
Vertex ab = middle(t.a, t.b);
Vertex bc = middle(t.b, t.c);
spanTriangles(xml3d, new Triangle(t.a, ac, ab), i - 1);
spanTriangles(xml3d, new Triangle(t.b, ab, bc), i - 1);
spanTriangles(xml3d, new Triangle(t.c, bc, ac), i - 1);
}
private static void addTriangle(Xml3d xml3d, Triangle t) {
addVertex(xml3d, t.a);
addVertex(xml3d, t.b);
addVertex(xml3d, t.c);
}
}
```
--------------------------------
### XMLBeam Mixin Implementation for Sorting SVG Elements
Source: https://xmlbeam.org/t07
This example code demonstrates how to use XMLBeam's projection mixin feature. It initializes an XBProjector, loads an SVG document, and adds a mixin implementation for the GraphicElement interface to enable sorting based on Y position. Finally, it sorts the graphic elements and updates the document.
```java
XBProjector xmlProjector = new XBProjector();
SVGDocument svgDocument = xmlProjector.io().fromURLAnnotation(SVGDocument.class);
xmlProjector.mixins().addProjectionMixin(GraphicElement.class, new Comparable() {
private GraphicElement me;
@Override
public int compareTo(GraphicElement o) {
return me.getYPosition().compareTo(o.getYPosition());
}
});
List list = svgDocument.getGraphicElements();
Collections.sort(list);
svgDocument.setGraphicElements(list);
```
--------------------------------
### Using XBAutoMap for XML Key-Value Access (Java)
Source: https://xmlbeam.org/autotypes
Explains how to use XBAutoMap to manage key-value pairs within an XML structure, similar to a map. It covers reading attribute values, creating new elements, and setting element values. The example also demonstrates the alternative usage with the @XBAuto annotation.
```Java
public interface Projection {
@XBRead("/root/foo")
XBAutoMap entries();
}
// Usage examples:
XBAutoMap map = projection.entries();
String attributeValue = map.get("subelement/@attribute"); // Read attribute of subelement below /root/foo/..
map.put("new/sub/structure", "new value"); // Create new elements and set value of element 'structure'
// Alternative using @XBAuto annotation:
@XBAuto("/root/foo")
Map entries();
```
--------------------------------
### Java: Reading Plist with Custom XPath and Non-Validating Factory
Source: https://xmlbeam.org/t15
This Java code demonstrates reading a plist file using XMLBeam. It includes a custom XML factories configuration to disable DTD validation and an externalizer to derive XPath from method names. The example projects the plist data into the PList interface and prints the extracted information.
```java
public class TestPlistAccess extends TutorialTestCase {
/**
* Every plist file has a DTD referenced which might be unavailable if you are on a non MacOs system.
* So we tweak the XBProjector configuration to ignore the DTD.
*/
private final class NonValidatingXMLFactoriesConfig extends DefaultXMLFactoriesConfig {
@Override
public DocumentBuilderFactory createDocumentBuilderFactory() {
try {
final DocumentBuilderFactory factory = super.createDocumentBuilderFactory();
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
return factory;
} catch (final ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
}
/**
* The projection in this tutorial does not define any XPath expression to the data.
* Instead we like to derive the XPath from the method name. Although this could be done
* in a single XPath expression, we split it up for two cases for readability:
* - Selecting all children of the following element of the key element, if an array is expected
* and
* - Selecting the first following element of the key element, in all other cases.
*/
public class PListExternalizer extends ExternalizerAdapter {
@Override
public String resolveXPath(final String annotationValue, final Method method, final Object[] args) {
final String keyValue = method.getName().substring(3);
if (method.getReturnType().isArray()) {
return "/plist/dict/key[.=\""+keyValue+"\"]/following-sibling::*[1]/child::*";
}
return "/plist/dict/key[.=\""+keyValue+"\"]/following-sibling::*[1]";
}
}
@Test
public void testReadPList() throws IOException {
final XBProjector projector = new XBProjector(new NonValidatingXMLFactoriesConfig());
projector.config().setExternalizer(new PListExternalizer());
final PList plist = projector.io().fromURLAnnotation(PList.class);
System.out.println(plist.getAuthor()+" ("+plist.getBirthdate()+")");
for (final String line:plist.getLines()) {
System.out.println(line);
}
}
}
```
--------------------------------
### XMLBeam Projection and Manipulation Example (Java)
Source: https://xmlbeam.org/t08
This Java code demonstrates using XMLBeam to project an XML document from a URL annotation, extract information like element names and attribute values, and then modify the document by setting a new root element projected from a DOM node.
```java
XBProjector projector = new XBProjector();
Document document = projector.io().fromURLAnnotation(Document.class);
Element element = document.getRootElement();
System.out.println(element.getName());
Element element2 = element.element("eelement");
System.out.println(element2.getText());
Attribute attribute = element2.attribute("eattribute");
System.out.println(attribute.getValue());
org.w3c.dom.Element newRootNode = ((DOMAccess)document).getDOMOwnerDocument().createElement("newRoot");
Element newRootElement = projector.projectDOMNode(newRootNode, Element.class);
document.setRootElement(newRootElement);
System.out.println(document);
```
--------------------------------
### Add XMLBeam Maven Dependency
Source: https://xmlbeam.org/download
This snippet shows how to add the XMLBeam library as a dependency to your Maven project. Ensure you have Maven installed and configured to access the central repository. This dependency allows you to use XMLBeam's features in your Java project.
```xml
org.xmlbeam
xmlprojector
1.4.26
```
--------------------------------
### Creating and Populating XHTML Document (Java)
Source: https://xmlbeam.org/t06
Demonstrates creating an empty XHTML document and populating it using the previously defined XHTML projection interface. It shows how to instantiate the projection and set various XHTML elements like namespace, language, title, and body content.
```java
XHTML xhtml = projector.projectEmptyDocument(XHTML.class);
xhtml.setRootNameSpace("http://www.w3.org/1999/xhtml").setRootLang("en");
xhtml.setTitle("This Is My Fine Title");
xhtml.setBody("Here some text...");
```
--------------------------------
### Add HTTP Request Properties in Java
Source: https://xmlbeam.org/refcards
When interacting with URLs, you can customize HTTP requests by adding properties like headers. This is useful for setting authentication credentials, content types, or other necessary request headers for GET or POST operations.
```java
Projection projection = projector.io().url(httpurl).addRequestProperty("key", "value").read(Projection.class);
Projection projection2 = projector.io().url(httpurl).addRequestProperties(props).read(Projection.class);
```
--------------------------------
### Projection API - XHTML Interface
Source: https://xmlbeam.org/t06
This section details the XHTML interface used for creating XHTML documents programmatically via projections. It includes methods for setting the root namespace, language, title, and body content.
```APIDOC
## Projection API
### Description
Defines the interface for creating XHTML documents from scratch using projections. Allows setting namespace, language, title, and body content.
### Interface
`public interface XHTML`
### Methods
- `@XBWrite("/html/@xmlns") XHTML setRootNameSpace(String ns);`
- Sets the root namespace for the HTML element.
- `@XBWrite("/html/@xml:lang") XHTML setRootLang(String lang);`
- Sets the root language for the HTML element.
- `@XBWrite("/html/head/title") XHTML setTitle(String title);`
- Sets the title of the HTML document.
- `@XBWrite("/html/body") XHTML setBody(String body);`
- Sets the body content of the HTML document.
### Example Usage
```java
XHTML xhtml = projector.projectEmptyDocument(XHTML.class);
xhtml.setRootNameSpace("http://www.w3.org/1999/xhtml").setRootLang("en");
xhtml.setTitle("This Is My Fine Title");
xhtml.setBody("Here some text...");
```
```
--------------------------------
### HTTP Basic Authentication in Java
Source: https://xmlbeam.org/refcards
XMLBeam simplifies setting up HTTP Basic Authentication for requests. You can generate the necessary authentication properties using IOHelper.createBasicAuthenticationProperty and then add them to the projector's I/O configuration.
```java
Map credentials = IOHelper.createBasicAuthenticationProperty("user", "pwd");
projector.io().url(httpurl).addRequestProperties(credentials).write(projection);
```
--------------------------------
### Define Element Interface with XMLBeam Annotations (Java)
Source: https://xmlbeam.org/t08
This Java interface defines the structure for an Element within an XML document, using XMLBeam annotations for various read and write operations like adding attributes, retrieving elements, and getting names and text content.
```java
public interface Element {
@XBRead(".")
Element addAttribute(Attribute attribute);
@XBWrite("@{1}")
Element addAttribute(String name, @XBValue String value);
@XBRead("@{0}")
Attribute attribute(String name);
@XBRead("count(@*)")
int attributeCount();
@XBRead("@*")
List attributes();
@XBRead("@{0}")
String attributeValue(String attributeName);
@XBRead("./{0}")
Element element(String name);
@XBRead("./*")
List elements();
@XBRead("name()")
String getName();
@XBRead(".")
String getText();
}
```
--------------------------------
### TestJenkinsConfigParsing Class for XMLBeam Projection
Source: https://xmlbeam.org/t02
This Java class demonstrates how to use XMLBeam to parse a Jenkins job configuration. It initializes the 'JenkinsJobConfig' projection using 'XBProjector' and includes test methods to iterate through builders and publishers, printing their names and associated information. Dependencies include JUnit annotations and XMLBeam library.
```java
public class TestJenkinsConfigParsing extends TutorialTestCase {
private JenkinsJobConfig config;
@Before
public void readJobConfig() throws IOException {
config = new XBProjector().io().fromURLAnnotation(JenkinsJobConfig.class);
}
@Test
public void testBuilderReading() {
for (Builder builder: config.getAllBuilders()) {
System.out.println("Builder: "+builder.getName()+" executes "+builder.getTargetsOrCommands() );
}
}
@Test
public void testPublishers() {
List publishers = config.getPublishers();
for (Publisher p : publishers) {
System.out.println("Publisher:"+ p.getName() + " contributed by plugin "+p.getPlugin());
}
}
}
```
--------------------------------
### Java Interface for Weather Data Projection with XMLBeam
Source: https://xmlbeam.org/t01
Defines a Java interface 'WeatherData' that uses XMLBeam's '@XBRead' annotation to map XML attributes and elements to interface methods. It includes a nested interface 'Coordinates' for grouping related attributes, demonstrating data projection and sub-projection capabilities.
```java
public interface WeatherData {
@XBRead("/weatherdata/weather/@searchlocation")
String getLocation();
@XBRead("/weatherdata/weather/current/@temperature")
int getTemperature();
@XBRead("/weatherdata/weather/@degreetype")
String getDegreeType();
@XBRead("/weatherdata/weather/current/@skytext")
String getSkytext();
/**
* This would be our "sub projection". A structure grouping two attribute
* values in one object.
*/
interface Coordinates {
@XBRead("@lon")
double getLongitude();
@XBRead("@lat")
double getLatitude();
}
@XBRead("/weatherdata/weather")
Coordinates getCoordinates();
}
```
--------------------------------
### Define Builder Interface Extending ModelElement with XPath Wildcards
Source: https://xmlbeam.org/t02
This Java interface, 'Builder', extends 'ModelElement' and includes a 'getTargetsOrCommands' method. It utilizes XPath wildcards ('child::targets | child::command') within the '@XBRead' annotation to project content from either 'targets' or 'command' child elements, illustrating flexible element selection.
```java
public interface Builder extends ModelElement {
/**
* Builder may invoke ant targets, maven goals or shell commands.
* @return The builders task, whatever this element is.
*/
@XBRead("child::targets | child::command")
String getTargetsOrCommands();
}
```
--------------------------------
### Using XBAutoValue for XML Attribute Getters/Setters (Java)
Source: https://xmlbeam.org/autotypes
Demonstrates how to use XBAutoValue to create Java interface methods that act as getters and setters for XML attributes. It covers reading, setting, checking for presence, removing, iterating, getting the attribute name, and renaming attributes, with all operations automatically updating the XML DOM.
```Java
public interface Example {
@XBRead("/foo/@bar")
XBAutoValue getBar();
}
// Usage examples:
String value = example.getBar().get(); // read the value
example.getBar().set("new value"); // sets the value
if (example.getBar().isPresent()) { // checks for existence
}
example.getBar().remove(); // removes attribute from foo element
for (String bar:example.getBar()) { // only invoked if attribute is present
}
String attributeName = example.getBar().getName(); // "bar" in this example
example.getBar().rename("bar2"); // rename the XML attribute 'bar' to 'bar2' in the XML
```
--------------------------------
### Java Code for XML Schema Handling with XMLBeam
Source: https://xmlbeam.org/t16
This Java code sets up an `XBProjector` configured with a `DocumentBuilderFactory` that includes an XML schema. It then uses the `Vegetables` projection to read data, demonstrating the retrieval of both explicitly set and schema-defaulted values.
```java
public class TestSchemaHandling extends TutorialTestCase {
Vegetables vegetables;
@Before
public void readVegetables() throws Exception {
XBProjector projector = new XBProjector(new DefaultXMLFactoriesConfig(){
private static final long serialVersionUID = 1L;
@Override
public DocumentBuilderFactory createDocumentBuilderFactory() {
DocumentBuilderFactory factory = super.createDocumentBuilderFactory();
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema schema = schemaFactory.newSchema(getClass().getResource("schema.xsd"));
factory.setSchema(schema);
} catch (SAXException e) {
throw new RuntimeException("Error loading schema", e);
}
return factory;
}
});
vegetables = projector.io().fromURLAnnotation(Vegetables.class);
}
@Test
public void testReadActualValue() {
assertEquals("red", vegetables.getVegetable("Tomato").getColor());
}
@Test
public void testReadDefaultValueDefinedInSchema() {
assertEquals("green", vegetables.getVegetable("Cucumber").getColor());
}
}
```
--------------------------------
### Define Publisher Interface Extending ModelElement with @XBRead
Source: https://xmlbeam.org/t02
This Java interface, 'Publisher', extends the 'ModelElement' interface and defines a 'getPlugin' method. The '@XBRead' annotation is used to extract the 'plugin' attribute from the XML element, demonstrating attribute projection.
```java
public interface Publisher extends ModelElement {
/**
* The Plugin name is located in an attribute of the configuration element.
* @return The plugin name which contributed this element.
*/
@XBRead("@plugin")
String getPlugin();
}
```
--------------------------------
### Create XBProjector Instance in Java
Source: https://xmlbeam.org/refcards
The XBProjector class is the central point for XML data operations. An instance can be created using its default constructor or by providing a custom XMLFactoriesConfiguration for specific DocumentBuilder, Transformer, or XPath implementations.
```java
XBProjector projector = new XBProjector();
```
--------------------------------
### Java Code to Read and Print Weather Data using XMLBeam
Source: https://xmlbeam.org/t01
Demonstrates how to use XMLBeam's 'XBProjector' to read weather data from a resource file ('WeatherData.xml') and project it into the 'WeatherData' Java interface. It then prints various pieces of information, including data from the nested 'Coordinates' projection.
```java
private void printWeatherData(String location) throws IOException {
final String fileURL = "resource://WeatherData.xml";
WeatherData weatherData = new XBProjector().io().url(fileURL).read(WeatherData.class);
System.out.println("The weather in " + weatherData.getLocation() + ":");
System.out.println(weatherData.getSkytext());
System.out.println("Temperature: " + weatherData.getTemperature() + "°" + weatherData.getDegreeType());
Coordinates coordinates = weatherData.getCoordinates();
System.out.println("The place is located at " + coordinates.getLatitude() + "," + coordinates.getLongitude());
}
```
--------------------------------
### Define JenkinsJobConfig Interface with @XBDocURL and @XBRead for Lists
Source: https://xmlbeam.org/t02
This Java interface, 'JenkinsJobConfig', uses the '@XBDocURL' annotation to declare the document origin ('resource://config.xml'). It defines methods to retrieve lists of 'Publisher' and 'Builder' objects using '@XBRead' with XPath expressions that select multiple elements ('//publishers/*', '//prebuilders/* | //builders/* | //postbuilders/*').
```java
@org.xmlbeam.annotation.XBDocURL("resource://config.xml")
public interface JenkinsJobConfig {
@XBRead("//publishers/*")
List getPublishers();
@XBRead("//prebuilders/* | //builders/* | //postbuilders/*")
List getAllBuilders();
}
```
--------------------------------
### Create Projection from Scratch in Java
Source: https://xmlbeam.org/refcards
XMLBeam allows creating projections for empty documents or elements. This enables bidirectional projection, where you can populate an empty structure by calling setter methods on the projection interface.
```java
Projection projection = projector.projectEmptyDocument(Projection.class);
Projection subProjection = projector.projectEmptyElement(name, Projection.class);
```
--------------------------------
### Use Maven POM Projection and Modify Project Name (Java)
Source: https://xmlbeam.org/t04
This Java code snippet demonstrates using the MavenPOM projection created with XMLBeam. It initializes the projector, loads the POM file, modifies the project name using the defined setter, and then iterates through the dependencies to check for self-references. It uses JUnit assertions for validation.
```java
MavenPOM pom = new XBProjector(Flags.TO_STRING_RENDERS_XML).io().fromURLAnnotation(MavenPOM.class);
pom.setName("New name");
assertTrue(pom.getDependencies().length>0);
for (Artifact artifact:pom.getDependencies()) {
if (artifact.equals(pom.getProjectId())) {
System.out.println("Hmm... your project depends on itself!");
throw new AssertionError();
}
}
```
--------------------------------
### JUnit Test for Dumping MindMap Data with XMLBeam
Source: https://xmlbeam.org/t11
This Java code provides a complete JUnit test case to demonstrate rendering a mindmap as formatted characters by splitting the input data. It uses XBProjector to load the mindmap and recursively walks through nodes to format and print the left and right sides.
```java
public class TestDumpMindMap {
private static final Comparator super String> STRING_LENGTH_COMPARATOR = new Comparator() {
@Override
public int compare(String o1, String o2) {
return Integer.valueOf(o1.length()).compareTo(o2.length());
}
};
@Test
public void dump() throws IOException {
MindMap mindMap = new XBProjector().io().fromURLAnnotation(MindMap.class);
List leftLines = new LinkedList();
List rightLines= new LinkedList();
walkNodes("", mindMap.getLeftNodes(), leftLines,true);
walkNodes("",mindMap.getRightNodes(),rightLines,false);
int maxLength = Collections.max(leftLines, STRING_LENGTH_COMPARATOR).length();
String rootText = mindMap.getRootNode().getText();
System.out.println(String.format("%1$- "+ maxLength + "s", "")+rootText);
String midSpace=rootText.replaceAll(".", " ");
for (String s : leftLines) {
String right=rightLines.isEmpty()?"":rightLines.get(0);
if (!rightLines.isEmpty()){rightLines.remove(0);};
String line = reverse(String.format("%1$- "+ maxLength + "s", s))+midSpace+right;
System.out.println(line);
}
for (String s:rightLines) {
String line=String.format("%1$- "+ maxLength + "s", "")+midSpace+s;
System.out.println(line);
}
}
private void walkNodes(String prefix, Node[] leftNodes, List lines,boolean reverse) {
for (Node n : leftNodes) {
lines.add((prefix + (reverse ? reverse(n.getText()) : n.getText()) ));
walkNodes(prefix + (n.getText()).replaceAll(".", " "), n.getSubNodes(), lines,reverse);
}
}
private String reverse(final String s) {
return new StringBuffer(s).reverse().toString();
}
}
```
--------------------------------
### Dynamic XPath with Parameter Names (Java 8+)
Source: https://xmlbeam.org/refcards
Illustrates using parameter names directly in XPath expressions for dynamic projections when using Java 8 or later with the '-parameters' javac option. This allows for more readable and maintainable dynamic XPath queries.
```java
@XBRead("/{parentNode}/{subnode}[@id='{id}']")
String readSomeValue(String parentNode,String subnode,int id);
```
--------------------------------
### Read/Write Projection to File in Java
Source: https://xmlbeam.org/refcards
The XBProjector provides convenient methods for reading XML from and writing XML to files. You can read directly into a projection or write a projection's content to a file, with an option to append to existing files.
```java
Projection projection = projector.io().file(file).read(Projection.class);
projector.io().file(file).write(projection);
projector.io().file(file).setAppend(true).write(projection);
```
--------------------------------
### XMLBeam Java Projection Interfaces
Source: https://xmlbeam.org/t16
These Java interfaces define the XML structure for XMLBeam projections. The `Vegetable` interface maps attributes, and the `Vegetables` interface uses `@XBRead` to query specific vegetables by name, leveraging the schema's namespace.
```java
public interface Vegetable {
@XBRead("@name")
String getName();
@XBRead("@color")
String getColor();
}
```
```java
@XBDocURL("resource://vegetables.xml")
public interface Vegetables {
@XBRead("/xbdefaultns:Vegetables/xbdefaultns:Vegetable[@name='{0}']")
Vegetable getVegetable(String name);
}
```
--------------------------------
### Define Maven POM Projection Interface with Setters (Java)
Source: https://xmlbeam.org/t04
This Java interface defines a projection for a Maven POM file using XMLBeam annotations. It includes methods to read artifact details (groupId, artifactId, version) and project name, as well as a setter to modify the project name. Dependencies are read as an array of Artifact objects.
```java
@XBDocURL("resource://pom.xml")
public interface MavenPOM {
/**
* When I see an artifact with id and group and version, I call it an artifact.
* (adapted from James Whitcomb Riley)
*/
public interface Artifact {
@XBRead("child::groupId")
String getGroupId();
@XBRead("child::artifactId")
String getArtifactId();
@XBRead("child::version")
String getVersion();
}
@XBRead("/project/name")
String getName();
@XBWrite("/project/name")
void setName(String name);
@XBRead("/project")
Artifact getProjectId();
@XBRead("/project/dependencies/dependency")
Artifact[] getDependencies();
}
```
--------------------------------
### Parse HTML Documents with XMLBeam JUnit Test
Source: https://xmlbeam.org/t10
Demonstrates parsing multiple HTML documents from Wikipedia using XMLBeam within a JUnit test. It fetches and processes pages for different programming languages, printing the creator and name of each. This code requires the XMLBeam library and JUnit.
```java
public class TestWikiAccess extends TutorialTestCase {
final private String[] PROGRAMMING_LANGUAGES = new String[] { "Java", "C++", "C", "Scala" };
@Test
public void wikiIt() throws IOException {
for (String name : PROGRAMMING_LANGUAGES) {
ProgrammingLanguage lang = new XBProjector().io().fromURLAnnotation(ProgrammingLanguage.class, name);
System.out.println(lang.getCreator() + " designed " + lang.getName());
}
}
}
```
--------------------------------
### Implement toString() with Mixin (Java 6 & 7)
Source: https://xmlbeam.org/faq
Shows how to override the toString() method for XMLBeam projections in Java 6 and 7 by using a mixin interface and registering it with the projector.
```java
public interface Projection extends MixinOverridingToString {
// Your projection methods here
@XBRead("...")
String getSomeValue();
}
```
```java
public interface MixinOverridingToString {
@Override
String toString();
}
```
```java
Object mixin = new Object() {
private Projection me;
@Override
public String toString() {
return "I have value " + me.getSomeValue();
};
};
projector.mixins().addProjectionMixin(Projection.class, mixin);
```
--------------------------------
### XHTML Projection Interface Definition (Java)
Source: https://xmlbeam.org/t06
Defines a Java interface for projecting XHTML content. It uses XMLBeam's @XBWrite annotation to map interface methods to specific XPath locations within the XHTML document. This interface allows programmatic manipulation of the document structure.
```java
public interface XHTML {
@XBWrite("/html/@xmlns")
XHTML setRootNameSpace(String ns);
@XBWrite("/html/@xml:lang")
XHTML setRootLang(String lang);
@XBWrite("/html/head/title")
XHTML setTitle(String title);
@XBWrite("/html/body")
XHTML setBody(String body);
}
```
--------------------------------
### XML Data: Complex Plist Structure
Source: https://xmlbeam.org/t15
This snippet shows a sample XML Property List (plist) file structure. It includes keys with string, array, and integer values, commonly used for data storage in OS X applications.
```xml
Author
Charles Robert Darwin
Lines
A man who dares to waste one hour of time has not discovered the value of life.
I have tried lately to read Shakespeare, and found it so intolerably dull that it nauseated me.
I love fools' experiments. I am always making them.
Birthdate
1809
```
--------------------------------
### Java Projection Interface for Dreambox Data
Source: https://xmlbeam.org/t09
Defines a Java interface 'Dreambox' for projecting data from a Dreambox device. It uses XMLBeam annotations like @XBDocURL and @XBRead to specify XML sources and paths. The interface includes methods to retrieve movies, services, events, and locations, demonstrating how to aggregate data from multiple external XML sources into a unified Java object structure.
```java
public interface Dreambox {
// This is the root XBDocURL of my device.
final static String BASE_URL = "http://192.168.1.44/web";
@XBDocURL(BASE_URL + "/movielist?dirname={0}")
@XBRead("/e2movielist/e2movie")
List getMovies(String location);
@XBDocURL(BASE_URL + "/getservices?sRef=1%3A7%3A1%3A0%3A0%3A0%3A0%3A0%3A0%3AFROM%20BOUQUET%20%22userbouquet.favourites.tv%22%20ORDER%20BY%20bouquet")
@XBRead("/e2servicelist/e2service")
List getServices();
@XBDocURL(BASE_URL + "/web/epgservice?sRef={0}")
@XBRead("/e2eventlist/e2event")
List getEvents(String serviceReference);
@XBDocURL(BASE_URL + "/web/getlocations")
@XBRead("e2locations/e2location")
List getLocations();
}
```
--------------------------------
### Dynamic XPath with Parameter Index (Pre-Java 8)
Source: https://xmlbeam.org/refcards
Shows the pre-Java 8 approach to dynamic projections, where parameter indices (e.g., {0}, {1}, {2}) are used within XPath expressions. This method is compatible with older Java versions but is less readable than using parameter names.
```java
@XBRead("/{0}/{1}[@id='{2}']")
String readSomeValue(String parentNode,String subnode,int id);
```
--------------------------------
### Test GraphML Creation using XMLBeam
Source: https://xmlbeam.org/t13
Provides JUnit test cases for verifying the functionality of the XMLBeam library in creating and manipulating graph structures. It demonstrates how to instantiate projections, set node properties, and add nodes and edges to a GraphML document.
```java
public class TestGraphMLCreation {
@Test
public void testGraphCreation() throws IOException {
Node node = new XBProjector(Flags.TO_STRING_RENDERS_XML).io().fromURLAnnotation(Node.class).rootElement();
node.setLabel("NodeLabel");
assertEquals("NodeLabel", node.getLabel());
node.setID("Nodeid");
assertEquals("Nodeid", node.getID());
}
@Test
public void testGraphNodeSetting() throws IOException {
GraphML graph = new XBProjector().io().fromURLAnnotation(GraphML.class);
Edge edge = new XBProjector().io().fromURLAnnotation(Edge.class).rootElement();
Node node = new XBProjector().io().fromURLAnnotation(Node.class).rootElement();
graph.addEdge("wutz", edge);
graph.addNode("huhu", node);
}
}
```
--------------------------------
### XMLBeam Projection for Plist Data
Source: https://xmlbeam.org/t15
This Java interface defines the structure for projecting plist data using XMLBeam annotations. It maps XML elements to Java methods, with @XBRead indicating data extraction.
```java
@XBDocURL("resource://example.plist")
public interface PList {
@XBRead()
String getAuthor();
@XBRead()
String[] getLines();
@XBRead()
int getBirthdate();
}
```
--------------------------------
### Custom Type Creation for XML Projection Getters
Source: https://xmlbeam.org/refcards
Explains how to configure a projection method to return a custom type by providing a String constructor or a static factory method (valueOf, of, parse, getInstance). This allows for flexible data type handling when reading XML data.
```java
public interface MyProjection {
@XBRead("some/path/to/data")
MyCustomType getData();
}
```
```java
public class MyCustomType {
public MyCustomType(final String data) {
//...
}
}
```
```java
public static MyCustomType valueOf(final String data) {
return somehowCreateInstanceFor(data);
}
public static MyCustomType of(final String data) {
return somehowCreateInstanceFor(data);
}
public static MyCustomType parse(final String data) {
return somehowCreateInstanceFor(data);
}
public static MyCustomType getInstance(final String data) {
return somehowCreateInstanceFor(data);
}
```
--------------------------------
### Read/Write Projection from/to URL in Java
Source: https://xmlbeam.org/refcards
XMLBeam supports reading and writing projections to URLs using various protocols, including file, HTTP, and HTTPS. For reading, the 'resource' protocol can be used to access Java resources. HTTP writing typically involves POSTing the document to the specified URL.
```java
Projection projection = projector.io().url(url).read(Projection.class);
projector.io().url(url).write(projection);
```
--------------------------------
### Define HTML Document Projection Interface
Source: https://xmlbeam.org/t10
Defines a projection interface for HTML documents, specifying how to extract the name and creator of a programming language from Wikipedia URLs. It uses annotations to map XML/HTML elements to Java methods. This requires the XMLBeam library.
```java
@XBDocURL("http://en.wikipedia.org/wiki/{0}_(programming_language)")
public interface ProgrammingLanguage {
@XBRead("//b[1]")
String getName();
@XBRead("normalize-space(//td[../th = \"Designed by\"])")
String getCreator();
}
```
--------------------------------
### Define Model Element Interface with @XBRead Annotation
Source: https://xmlbeam.org/t02
This Java interface defines a base model element with a 'name' getter, utilizing the '@XBRead' annotation to specify the XPath expression for retrieving the element's name. It demonstrates how to use XPath functions like 'name()' for data projection.
```java
public interface ModelElement {
/**
* Getter may use XPath functions.
* @return Name of the XML Element which is projected to this object.
*/
@XBRead("name()")
String getName();
}
```
--------------------------------
### EclipseFormatterConfigFile API
Source: https://xmlbeam.org/t03
This section details the Projection API for accessing Eclipse code formatter profiles from an XML file. It demonstrates how to define Java interfaces that map directly to XML structures and attributes, enabling dynamic data retrieval.
```APIDOC
## EclipseFormatterConfigFile API
### Description
This API allows fetching and processing Eclipse code formatter settings stored in an XML file. It uses dynamic projections to map XML elements and attributes to Java interface methods.
### Method
N/A (This describes an interface definition, not an HTTP endpoint)
### Endpoint
N/A (This describes an interface definition, not an HTTP endpoint)
### Parameters
N/A
### Request Body
N/A
### Request Example
```java
EclipseFormatterConfigFile configFile = new XBProjector().io().fromURLAnnotation(EclipseFormatterConfigFile.class);
System.out.println("Profile names:" + configFile.getProfileNames());
for (Setting setting:configFile.getAllSettingsForProfile("Some Profile")) {
System.out.println(setting.getName() + " -> " + setting.getValue());
}
```
### Response
#### Success Response (Interface Definition)
- **EclipseFormatterConfigFile** (interface) - Represents the structure of the Eclipse formatter XML file.
- **Setting** (interface) - Represents a single formatter setting with `name` and `value`.
- **getName()** (String) - Returns the name of the formatter setting.
- **getValue()** (String) - Returns the value of the formatter setting.
- **getProfileNames()** (List) - Returns a list of all profile names found in the XML.
- **getAllSettingsForProfile(String profileName)** (List) - Returns a list of all settings for a given profile name.
#### Response Example
Profile names:[Some Profile, Another Profile]
Some Profile -> false
Some Profile -> 16
...
```
--------------------------------
### Read or Write XML Projection via InputStream/OutputStream
Source: https://xmlbeam.org/refcards
Demonstrates how to read an XML projection from an InputStream and write a projection to an OutputStream using the XMLBeam projector. This method handles the serialization and deserialization of Java objects to/from XML streams.
```java
Projection projection = projector.io().stream(is).read(Projection.class);
Projection projectionWithSystemID = projector.io().stream(is).setSystemID(systemID).read(Projection.class);
projector.io().stream(os).write(projection);
```
--------------------------------
### Java Interface for XML3D Data Projection
Source: https://xmlbeam.org/t12
Defines a Java interface `Xml3d` for projecting and manipulating 3D data within an XML document using XMLBeam annotations. It specifies read and write operations for 'index', 'position', and 'normal' attributes, leveraging `@XBRead` and `@XBWrite` annotations for data mapping. The interface also uses `@XBDocURL` to specify the template document.
```java
@XBDocURL("resource://xml3d_template.html")
public interface Xml3d {
@XBRead("/html/body/xml3d/mesh/int[@name='index']")
String getIndexes();
@XBWrite("/html/body/xml3d/mesh/int[@name='index']")
Xml3d setIndexes(String indexes);
@XBRead("/html/body/xml3d/mesh/float3[@name='position']")
String getPositions();
@XBWrite("/html/body/xml3d/mesh/float3[@name='position']")
Xml3d setPositions(String positions);
@XBRead("/html/body/xml3d/mesh/float3[@name='normal']")
String getNormals();
@XBWrite("/html/body/xml3d/mesh/float3[@name='normal']")
Xml3d setNormals(String normals);
}
```
--------------------------------
### XML Schema Definition with Defaults
Source: https://xmlbeam.org/t16
This XML schema defines the structure for Vegetable elements, including attributes like 'name' and 'color'. It specifies 'name' as required and 'color' with a default value of 'green'.
```xml
```
--------------------------------
### Project XML Data using Java Interface with XMLBeam
Source: https://xmlbeam.org/t03
This Java code snippet demonstrates how to use XMLBeam to project XML data into Java objects defined by an interface. It reads an XML file using a URL annotation and then accesses specific data, such as profile names and settings. This requires the XMLBeam library and a correctly defined interface like EclipseFormatterConfigFile.
```java
EclipseFormatterConfigFile configFile = new XBProjector().io().fromURLAnnotation(EclipseFormatterConfigFile.class);
System.out.println("Profile names:" + configFile.getProfileNames());
for (Setting setting : configFile.getAllSettingsForProfile("Some Profile")) {
System.out.println(setting.getName() + " -> " + setting.getValue());
}
```
--------------------------------
### Read/Write Projection via @XBDocURL Annotation in Java
Source: https://xmlbeam.org/refcards
The @XBDocURL annotation on a projection interface can specify the source document URL. The XBProjector can then use this annotation to read from or write to the specified URL, supporting parameters for the operation.
```java
Projection projection = projector.io().fromURLAnnotation(Projection.class, params);
projector.io().toURLAnnotationViaPOST(projectionInterface, projection, params);
```