{"id":17323752,"url":"https://github.com/jmurty/java-xmlbuilder","last_synced_at":"2025-04-04T11:11:59.123Z","repository":{"id":14737149,"uuid":"17458041","full_name":"jmurty/java-xmlbuilder","owner":"jmurty","description":"XML Builder is a utility that allows simple XML documents to be constructed using relatively sparse Java code","archived":false,"fork":false,"pushed_at":"2020-10-13T03:28:14.000Z","size":184,"stargazers_count":110,"open_issues_count":2,"forks_count":26,"subscribers_count":16,"default_branch":"master","last_synced_at":"2025-03-28T10:05:53.776Z","etag":null,"topics":["java","java-xmlbuilder","jaxp","xml","xmlbuilder","xpath","xpath-query"],"latest_commit_sha":null,"homepage":null,"language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"isbib/every-week","license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jmurty.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":null,"funding":null,"license":"LICENSE-2.0.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-03-05T22:48:04.000Z","updated_at":"2025-02-24T14:22:55.000Z","dependencies_parsed_at":"2022-09-10T17:21:47.968Z","dependency_job_id":null,"html_url":"https://github.com/jmurty/java-xmlbuilder","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jmurty%2Fjava-xmlbuilder","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jmurty%2Fjava-xmlbuilder/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jmurty%2Fjava-xmlbuilder/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jmurty%2Fjava-xmlbuilder/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jmurty","download_url":"https://codeload.github.com/jmurty/java-xmlbuilder/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247166168,"owners_count":20894654,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["java","java-xmlbuilder","jaxp","xml","xmlbuilder","xpath","xpath-query"],"created_at":"2024-10-15T14:08:28.128Z","updated_at":"2025-04-04T11:11:59.093Z","avatar_url":"https://github.com/jmurty.png","language":"Java","readme":"java-xmlbuilder\n===============\n\n[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.jamesmurty.utils/java-xmlbuilder/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.jamesmurty.utils/java-xmlbuilder)\n\n![Build](https://github.com/jmurty/java-xmlbuilder/workflows/Build/badge.svg) ![Codecov](https://github.com/jmurty/java-xmlbuilder/workflows/Codecov/badge.svg)\n\n[![codecov](https://codecov.io/gh/jmurty/java-xmlbuilder/branch/master/graph/badge.svg)](https://codecov.io/gh/jmurty/java-xmlbuilder)\n\nXML Builder is a utility that allows simple XML documents to be constructed\nusing relatively sparse Java code.\n\nIt allows for quick and painless creation of XML documents where you might\notherwise be tempted to use concatenated strings, and where you would rather\nnot face the tedium and verbosity of coding with\n[JAXP](http://jaxp.dev.java.net/).\n\nInternally, XML Builder uses JAXP to build a standard W3C Document model (DOM)\nthat you can easily export as a string, or access directly to manipulate\nfurther if you have special requirements.\n\n### License\n\n[Apache License Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)\n\nXMLBuilder versus XMLBuilder2\n-----------------------------\n\nSince version 1.1 this library provides two builder implementations and APIs:\n\n * `XMLBuilder` – the original API – follows standard Java practice of\n   re-throwing lower level checked exceptions when you do things like create a\n   new document.\n   You must explicitly `catch` these checked exceptions in your codebase, even\n   though they are unlikely to occur in tested code.\n * `XMLBuilder2` is a newer API that removes checked exceptions altogether, and\n   will instead wrap and propagate lower level exceptions in an unchecked\n   `XMLBuilderRuntimeException`.\n   Use this class if you don't like the code mess or overhead of try/catching\n   many low-level exceptions that are unlikely to occur in practice.\n\nBoth these versions work identically apart from the handling of errors, so you\ncan use whichever version you prefer or \"upgrade\" from one to the other in\nexisting code.\n\nQuick Example\n-------------\n\nEasily build XML documents using code structured like the final document.\n\nThis code:\n\n```java\nXMLBuilder2 builder = XMLBuilder2.create(\"Projects\")\n    .e(\"java-xmlbuilder\").a(\"language\", \"Java\").a(\"scm\",\"SVN\")\n        .e(\"Location\").a(\"type\", \"URL\")\n            .t(\"http://code.google.com/p/java-xmlbuilder/\")\n        .up()\n    .up()\n    .e(\"JetS3t\").a(\"language\", \"Java\").a(\"scm\",\"CVS\")\n        .e(\"Location\").a(\"type\", \"URL\")\n            .t(\"http://jets3t.s3.amazonaws.com/index.html\");\n```\n\nProduces this XML document:\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cProjects\u003e\n    \u003cjava-xmlbuilder language=\"Java\" scm=\"SVN\"\u003e\n        \u003cLocation type=\"URL\"\u003ehttp://code.google.com/p/java-xmlbuilder/\u003c/Location\u003e\n    \u003c/java-xmlbuilder\u003e\n    \u003cJetS3t language=\"Java\" scm=\"CVS\"\u003e\n        \u003cLocation type=\"URL\"\u003ehttp://jets3t.s3.amazonaws.com/index.html\u003c/Location\u003e\n    \u003c/JetS3t\u003e\n\u003c/Projects\u003e\n```\n\nGetting Started\n---------------\n\nSee further example usage below and in the\n[JavaDoc documentation](http://s3.james.murty.co/java-xmlbuilder/index.html).\n\nDownload a Jar file containing the latest version\n[java-xmlbuilder-1.3.jar](http://s3.james.murty.co/java-xmlbuilder/java-xmlbuilder-1.3.jar).\n\nMaven users can add this project as a dependency with the following additions\nto a POM.xml file:\n\n```maven\n\u003cdependencies\u003e\n  . . .\n  \u003cdependency\u003e\n    \u003cgroupId\u003ecom.jamesmurty.utils\u003c/groupId\u003e\n    \u003cartifactId\u003ejava-xmlbuilder\u003c/artifactId\u003e\n    \u003cversion\u003e1.3\u003c/version\u003e\n  \u003c/dependency\u003e\n  . . .\n\u003c/dependencies\u003e\n```\n\nHow to use the XMLBuilder\n-------------------------\n\nRead below for examples that show how you would use the XMLBuilder utility to\ncreate and manipulate XML documents like the following:\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cProjects\u003e\n    \u003cjava-xmlbuilder language=\"Java\" scm=\"SVN\"\u003e\n        \u003cLocation type=\"URL\"\u003ehttp://code.google.com/p/java-xmlbuilder/\u003c/Location\u003e\n    \u003c/java-xmlbuilder\u003e\n    \u003cJetS3t language=\"Java\" scm=\"CVS\"\u003e\n        \u003cLocation type=\"URL\"\u003ehttp://jets3t.s3.amazonaws.com/index.html\u003c/Location\u003e\n    \u003c/JetS3t\u003e\n\u003c/Projects\u003e\n```\n\n### Create a New XML Document\n\nTo begin, you create a new builder and XML document by specifying the name of\nthe document's root element. See the parsing methods below if you want to start\nwith an existing XML document.\n\n```java\nXMLBuilder builder = XMLBuilder.create(\"Projects\");\n```\n\nThe XMLBuilder object returned by the `create` method, and by all other XML\nmanipulation methods, provides methods that you can use to add more nodes to\nthe document. For example, to add the `java-xmlbuilder` and `JetS3t` nodes to\nthe root element you could do the following.\n\n```java\nXMLBuilder e1 = builder.element(\"java-xmlbuilder\");\nXMLBuilder e2 = builder.element(\"JetS3t\");\n```\n\nAnd to add attributes or further sub-elements to the two new elements, you\ncould call the appropriate methods on the variables assigned to each new node\nlike so:\n\n```java\ne1.attribute(\"language\", \"Java\");\ne1.attribute(\"scm\", \"SVN\");\n```\n\nThis is straight-forward enough, but it is far more verbose than necessary\nbecause the code does not take advantage of XMLBuilder's method-chaining\nfeature.\n\n### Method Chaining\n\nEvery XMLBuilder method that adds something to the XML document will return an\nXMLBuilder object that represents either a newly-added element, or the element\nto which something has been added.  This feature means that you can chain\ntogether many method calls without the need to assign intermediate objects to\nvariables.\n\nWith this in mind, here is code that performs the same job as the code above\nwithout any unnecessary variables.\n\n```java\nXMLBuilder builder = XMLBuilder.create(\"Projects\")\n    .element(\"java-xmlbuilder\")\n        .attribute(\"language\", \"Java\")\n        .attribute(\"scm\", \"SVN\")\n        .element(\"Location\")\n        .up()\n    .up()\n    .element(\"JetS3t\");\n```\n\nThere are two important things to notice in the code above:\n\n  * When you add a new element to the document with the `element` method, the\n    XMLBuilder node returned will represent that new element. If you invoke\n    methods on this node, attributes and elements will be added to the new node\n    rather than to the document's root.\n  * Once you have finished adding items to a new element, you can call the\n    `up()` method to retrieve the XMLBuilder node that represents the parent of\n    the current node. If you balance every call to `element()` with a call to\n    `up()`, you can write code that closely resembles the structure of the XML\n    document you are creating.\n\n### Shorthand Methods\n\nTo make your XML building code even shorter and easier to type, there are\nshorthand synonyms for every XML manipulation method. Instead of calling\n`element()` you can use the `elem()` or `e()` methods, and instead of typing\n`attribute()` you can use `attr()` or `a()`.\n\nHere is the complete code to build our example XML document using shorthand\nmethods.\n\n```java\nXMLBuilder builder = XMLBuilder.create(\"Projects\")\n    .e(\"java-xmlbuilder\")\n        .a(\"language\", \"Java\")\n        .a(\"scm\",\"SVN\")\n        .e(\"Location\")\n            .a(\"type\", \"URL\")\n            .t(\"http://code.google.com/p/java-xmlbuilder/\")\n        .up()\n    .up()\n    .e(\"JetS3t\")\n        .a(\"language\", \"Java\")\n        .a(\"scm\",\"CVS\")\n        .e(\"Location\")\n            .a(\"type\", \"URL\")\n            .t(\"http://jets3t.s3.amazonaws.com/index.html\");\n```\n\nThe following methods are available for adding items to the XML document:\n\n| XML Node             | Methods                    |\n| -------------------- | -------------------------- |\n| Element              | `element`, `elem`, `e`     |\n| Attribute            | `attribute`, `attr`, `a`   |\n| Text (Element Value) | `text`, `t`                |\n| CDATA                | `cdata`, `data`, `d`       |\n| Comment              | `comment`, `cmnt`, `c`     |\n| Process Instruction  | `instruction`, `inst`, `i` |\n| Reference            | `reference`, `ref`, `r`    |\n\n### Output\n\nXMLBuilder includes two convenient methods for outputting a document.\n\nYou can use the `toWriter` method to print the document to an output stream or\nfile:\n```java\nPrintWriter writer = new PrintWriter(new FileOutputStream(\"projects.xml\"));\nbuilder.toWriter(writer, outputProperties);\n```\n\nOr you can convert the document straight to a text string:\n```java\nbuilder.asString(outputProperties);\n```\n\nBoth of these output methods take an `outputProperties` parameter that you can\nuse to control how the output is generated. Any output properties you provide\nare forwarded to the underlying Transformer object that is used to serialize\nthe XML document.\n\nYou might specify any non-standard properties like so:\n\n```java\nProperties outputProperties = new Properties();\n\n// Explicitly identify the output as an XML document\noutputProperties.put(javax.xml.transform.OutputKeys.METHOD, \"xml\");\n\n// Pretty-print the XML output (doesn't work in all cases)\noutputProperties.put(javax.xml.transform.OutputKeys.INDENT, \"yes\");\n\n// Get 2-space indenting when using the Apache transformer\noutputProperties.put(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n\n// Omit the XML declaration header\noutputProperties.put(\n    javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, \"yes\");\n```\n\nIf you do not wish to change the default properties for your output, you can\nprovide a null value for `outputProperties`.\n\n### Accessing the Underlying Document\n\nBecause XMLBuilder merely acts as a layer on top of the standard JAXP XML\ndocument building tools, you can easily access the underlying Element or\nDocument objects if you need to manipulate them in ways that XMLBuilder does\nnot allow.\n\nTo obtain the Element represented by any given XMLBuilder node:\n```java\norg.w3c.dom.Element element = xmlBuilderNode.getElement();\n```\n\nTo obtain the entire XML document:\n```java\norg.w3c.dom.Document doc = builder.getDocument();\n```\n\nYou can also use the `root()` method to quickly obtain the builder object that\nrepresents the document's root element, no matter deep an element hierarchy\nyour code has built:\n\n```java\norg.w3c.dom.Element rootElement =\n    XMLBuilder.create(\"This\")\n        .e(\"Element\")\n            .e(\"Hierarchy\")\n                .e(\"Is\")\n                    .e(\"Really\")\n                        .e(\"Very\")\n                            .e(\"Deep\")\n                                .e(\"Indeed\")\n    .root().getElement();\n```\n\n### Parse XML\n\nIf you already have an XML document to which you need to add nodes or\nattributes, you can create a new XMLBuilder instance by parsing an\n`InputSource`, `String`, or `File`:\n\n```java\nXMLBuilder builder = XMLBuilder.parse(YOUR_XML_DOCUMENT_STRING);\n```\n\nParsing an existing document will produce an XMLBuilder object pointing at the\ndocument's root Element node. If you add elements or attributes to this builder\nobject, they will be added to the document's root element.\n\nIf you need to add nodes elsewhere in the parsed document, you will need to\nfind the correct location in the document using XPath statements.\n\n### Find Nodes with XPath\n\nTo add nodes at a specific point in an XML document, you can use XPath to\nobtain an XMLBuilder at the correct location. The `XMLBuilder#xpathFind` method\ntakes an XPath query string and returns a builder object located at the *first*\nElement that matches the query.\n\n```java\nXMLBuilder firstLocationBuilder = builder.xpathFind(\"//Location\");\n```\n\nNote that the XPath query provided to this method *must resolve to at least one\nElement node*.  If the query does not match any nodes, or if the first match is\nanything other than an Element, the method will throw an\nXPathExpressionException.\n\nLike all other XMLBuilder methods, this method can be easily chained to others\nwhen adding nodes.  Here is an example that adds a second element, `Location2`,\ninside the `JetS3t` element of our example document.\n\n```java\nbuilder.xpathFind(\"//JetS3t\").elem(\"Location2\").attr(\"type\", \"Testing\");\n```\n\nTo produce:\n\n```xml\n\u003cProjects\u003e\n  \u003cjava-xmlbuilder language=\"Java\" scm=\"SVN\"\u003e\n    \u003cLocation type=\"URL\"\u003ehttp://code.google.com/p/java-xmlbuilder/\u003c/Location\u003e\n  \u003c/java-xmlbuilder\u003e\n  \u003cJetS3t language=\"Java\" scm=\"CVS\"\u003e\n    \u003cLocation type=\"URL\"\u003ehttp://jets3t.s3.amazonaws.com/index.html\u003c/Location\u003e\n    \u003cLocation2 type=\"Testing\"/\u003e\n  \u003c/JetS3t\u003e\n\u003c/Projects\u003e\n```\n\n### Configuring advanced features\n\nWhen creating or parsing a document you can enable and disable advanced\nfeatures by using the more explicit versions of the `parse()` and `create()`\nconstructors.\n\nYou can:\n\n* use the `enableExternalEntities` flag to enable or disable external entities.\n  NOTE: you should leave these disabled, as they are by default, unless you\n  really need them because they open you to XML External Entity (XXE) injection\n  attacks.\n* use the `isNamespaceAware` flag to enable or disable namespace awareness in\n  the underlying `DocumentBuilderFactory`.\n\n\nRelease History\n---------------\n\nSee this project's version history in\n[CHANGES.md](https://github.com/jmurty/java-xmlbuilder/blob/master/CHANGES.md)\n\nThis project was previously hosted on Google Code at\n[https://code.google.com/p/java-xmlbuilder/](https://code.google.com/p/java-xmlbuilder/).\nPlease refer to this old location for historical issue reports and user\nquestions.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjmurty%2Fjava-xmlbuilder","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjmurty%2Fjava-xmlbuilder","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjmurty%2Fjava-xmlbuilder/lists"}