Common

Date Handing

Reflection

IO

HTTP Request

Cryptography

Misc.

XmlHelper

The XmlHelper class provides methods for parsing XML documents, retrieving elements, and converting nodes to maps. These methods can be used for processing and manipulating XML data.

All builders created by initBuilder() apply security restrictions that disable DTD declarations, external entities, external DTD/schema access, XInclude, and entity-reference expansion. Consequently, getRoot, parseXML, xPath, and MapTool.xmlToMap reject XXE payloads. Parse failures use sanitized messages and never append the complete XML input.

Methods

1. initBuilder()

Initializes a DocumentBuilder for XML parsing.

Example:

DocumentBuilder builder = XmlHelper.initBuilder();
// builder will be a new DocumentBuilder instance

2. xPath(String xml, String xpath, Consumer<Node> fn)

Retrieves nodes from an XML document using an XPath expression and processes them with a given function.

Example:

XmlHelper.xPath("path/to/xml/file.xml", "/root/element", node -> {
    // Process the node
    System.out.println(node.getTextContent());
});

3. parseXML(String xml, BiConsumer<Node, NodeList> fn)

Parses an XML string and processes the root element and its children with a given function.

Example:

String xmlContent = "<root><child>Content</child></root>";
XmlHelper.parseXML(xmlContent, (node, nodeList) -> {
    // Process the root element and its children
    System.out.println(node.getNodeName());
    for (int i = 0; i < nodeList.getLength(); i++) {
        System.out.println(nodeList.item(i).getTextContent());
    }
});

4. getRoot(String xml)

Retrieves the root element of an XML string.

Example:

String xmlContent = "<root><child>Content</child></root>";
Element root = XmlHelper.getRoot(xmlContent);
// root will be the <root> element

5. nodeAsMap(String xml, String xpath)

Converts the attributes of a node to a map.

Example:

Map<String, String> attributes = XmlHelper.nodeAsMap("path/to/xml/file.xml", "/root/element");
// attributes will contain the attributes of the <element> node

getNodeAttribute(Node, String) returns null when the node has no attribute map or when the requested attribute is absent.