Class XMLHelper
java.lang.Object
net.simplace.core.service.XMLHelper
Helper methods for XML operations based on JDOM2: parsing, serialising, reading attributes and XPath queries.
Instance methods use one SAX builder (with DTDResolver) per thread and one shared pretty-printing outputter;
use getInstance() to get the shared instance.
- Author:
- Andreas Enders
-
Method Summary
Modifier and TypeMethodDescriptionstatic final org.jdom2.ElementaddElement(org.jdom2.Element aElement, String aName, String aValue) Adds a new child element with text content, using the namespace of the parent.static voidaddTextToChildThatMayExist(org.jdom2.Element aParentElement, String aChildName, String aValue) Appends text to the child of aParentElement with the name aChildName.static booleancheckAttributeExists(org.jdom2.Element aVarElement, String aString) Checks whether an element has an attribute.static booleancheckAttributeNotEmpty(org.jdom2.Element aVarElement, String aString) Checks whether an element has an attribute with a non-blank value.static booleancheckValueExists(org.jdom2.Element aVarElement) Checks whether an element has non-blank text content.static org.jdom2.ElementcreateChoiceElement(String aId, String aTitle, String aRequired, String aEnabled, String aType, String aLocalize, String aMultiselect, String aDefault, Map<String, String> aOptions) Creates a form field element<choice>with<option>children.static org.jdom2.ElementcreateDoubleElement(String aId, String aTitle, String aRequired, String aEnabled, String aMin, String aMax, String aType, String aDefault) Creates a form field element<double>.static org.jdom2.ElementcreateFieldElement(String aName, String aTitle, String aId, String aRequired, String aEnabled, String aDefault) Creates a form field element with the common attributes.static org.jdom2.ElementcreateIntegerElement(String aId, String aTitle, String aRequired, String aEnabled, String aMin, String aMax, String aType, String aDefault) Creates a form field element<integer>.static org.jdom2.ElementcreateParameterElement(String aParameter, Object aValue) Creates an element<parameter key="aParameter">aValue</parameter>.static org.jdom2.ElementCreates a form field element<text>.static List<org.jdom2.Element> evaluateXPath(org.jdom2.Document aDoc, String aExpression) Evaluates an XPath expression on a document and returns the matching elements.static List<org.jdom2.Element> evaluateXPath(org.jdom2.Element aElement, String aExpression) Evaluates an XPath expression relative to an element and returns the matching elements.static StringevaluateXPathSingleResult(org.jdom2.Document aDoc, String aExpression) Evaluates an XPath expression on a document and returns the first result as string.static org.jdom2.DocumentgenerateProjectXML(String aProjectDataFile, List<FWSimVariable<?>> aVars, Map<FWSimVariable<?>, String> aSensitivityVarsMap, org.jdom2.Element aOutputsElement) Generates a project XML document that reads the project data from a CSV file.static final StringgetAttributeValueOrEmptyString(org.jdom2.Element aElement, String aAtrributeValue) Returns the value of an attribute, or an empty string if it does not exist.static final StringgetAttributeValueOrNull(org.jdom2.Element aElement, String aAtrributeValue) Returns the value of an attribute, ornullif it does not exist or is empty.static final booleangetBooleanAttributeValue(org.jdom2.Element aElement, String aName, boolean aDefault) Returns the value of an attribute as boolean.getCommaSeparatedList(org.jdom2.Element aElement, String aAttributeName) Reads an attribute from all child elements of an element and joins the values with commas.org.jdom2.DocumentgetDocumentFromStream(InputStream tFileIn) Parses an XML stream and returns the document.org.jdom2.DocumentgetDocumentFromString(String aString) Parses an XML string and returns the document.org.jdom2.ElementgetElementFromFile(File aFile) Parses an XML file and returns its root element.org.jdom2.ElementgetElementFromFile(File aFile, String aEncoding) Parses an XML file with the given character encoding and returns its root element.org.jdom2.ElementgetElementFromReader(Reader aReader) Parses XML from a reader and returns its root element.org.jdom2.ElementgetElementFromStream(InputStream tFileIn) Parses an XML stream and returns its root element.org.jdom2.ElementgetElementFromString(String aXMLContent) Parses an XML string and returns its root element.static XMLHelperReturns the shared instance, creating it on first call.static <T extends Number>
TgetNumberAttributeValue(org.jdom2.Element aElement, String aAttr, Class<T> aNumberType, T aDefault) Returns the value of an attribute converted to a number type.static org.jdom2.ElementgetOrCreateChild(org.jdom2.Element aParentElement, String aChildName) Returns the child element of aParentElement with the given name.getRootAttribute(String aXMLString, String aAttributeName) Reads an attribute of the root element of an XML string.getRootIDAttribute(String aXMLString) Reads theidattribute of the root element of an XML string.getRootNameAttribute(String aXMLString) Reads thenameattribute of the root element of an XML string.booleanisXMLWellFormed(String aXMLString) Checks whether a string is well-formed XML.outputToString(org.jdom2.Document aDocument) Serialises a document to a pretty-printed XML string.outputToString(org.jdom2.Element aElement) Serialises an element to a pretty-printed XML string.outputToStringWithDefault(org.jdom2.Document aDocument, String aDefault) Serialises a document to a pretty-printed XML string.outputToStringWithDefault(org.jdom2.Element aElement, String aDefault) Serialises an element to a pretty-printed XML string.removeChildren(String aXMLString, String aName) Removes all direct children of the root element with a certain name from an XML string.static StringReplaces all occurrences of a string (literally, not as regular expression).static StringReplaces attribute values in an XML string: every occurrence ofattribute="key"is replaced byattribute="value"for each entry of the map.static org.jdom2.ElementselectSingleElement(Object aContext, String aExpression) Returns the first element selected by an XPath expression (replaces the deprecatedorg.jdom2.xpath.XPath.selectSingleNode).static Double[]toDoubleArray(List<org.jdom2.Element> aChildren) Parses the text of each element as double.static Double[][]toDoubleMatrix(List<org.jdom2.Element> aChildren) Parses a matrix: each element is a row, itsvaluechildren are the columns.static Integer[]toIntArray(List<org.jdom2.Element> aChildren) Parses the text of each element as integer.static String[]toStringArray(List<org.jdom2.Element> aChildren) Returns the trimmed text of each element.transformElementToMap(org.jdom2.Element aElement) Transforms theparameterchildren of an element into a map from theirkeyattribute to their text.static org.jdom2.ElementtransformMapToElement(Map<String, Object> aParameterMap, String aNameOfRootElement) Transforms a map into an element with oneparameterchild per entry.
-
Method Details
-
getInstance
Returns the shared instance, creating it on first call.- Returns:
- the shared instance
-
getRootIDAttribute
-
replace
Replaces all occurrences of a string (literally, not as regular expression).- Parameters:
aString- string to search inaToBeReplacedString- string to search for; must not be emptyaReplaceWithString- replacement- Returns:
- the resulting string
-
replaceAttribute
public static String replaceAttribute(String aString, Map<String, Object> aReplacements, String aAttribute) Replaces attribute values in an XML string: every occurrence ofattribute="key"is replaced byattribute="value"for each entry of the map.- Parameters:
aString- XML stringaReplacements- map from old to new attribute values; the values must be stringsaAttribute- name of the attribute- Returns:
- the resulting string
-
getRootNameAttribute
-
outputToString
Serialises an element to a pretty-printed XML string.- Parameters:
aElement- element to serialise- Returns:
- the XML string
- Throws:
IOException- if serialising fails
-
outputToString
Serialises a document to a pretty-printed XML string.- Parameters:
aDocument- document to serialise- Returns:
- the XML string
- Throws:
IOException- if serialising fails
-
getElementFromString
public org.jdom2.Element getElementFromString(String aXMLContent) throws org.jdom2.JDOMException, IOException Parses an XML string and returns its root element.- Parameters:
aXMLContent- XML document as string- Returns:
- the root element
- Throws:
org.jdom2.JDOMException- if the string is not well-formed XMLIOException- if reading fails
-
outputToStringWithDefault
Serialises an element to a pretty-printed XML string. If the element isnullor an error occurs, a default string is returned.- Parameters:
aElement- element to serialiseaDefault- string to return on error- Returns:
- the XML string, or aDefault
-
getCommaSeparatedList
Reads an attribute from all child elements of an element and joins the values with commas.- Parameters:
aElement- parent elementaAttributeName- name of the attribute to read from each child- Returns:
- comma separated list of the values (missing attributes appear as
null), an empty string if there are no children, ornullif aElement isnull
-
outputToStringWithDefault
Serialises a document to a pretty-printed XML string. If an error occurs (e.g. the document isnull), a default string is returned.- Parameters:
aDocument- document to serialiseaDefault- string to return on error- Returns:
- the XML string, or aDefault
-
getRootAttribute
Reads an attribute of the root element of an XML string. Parse errors are logged.- Parameters:
aXMLString- XML document as stringaAttributeName- name of the attribute- Returns:
- the attribute value, or
nullif it does not exist or the string cannot be parsed
-
removeChildren
Removes all direct children of the root element with a certain name from an XML string.- Parameters:
aXMLString- XML document as stringaName- name of the children to remove- Returns:
- the resulting pretty-printed XML string, or the original string if it cannot be parsed
-
addElement
public static final org.jdom2.Element addElement(org.jdom2.Element aElement, String aName, String aValue) Adds a new child element with text content, using the namespace of the parent.- Parameters:
aElement- parent elementaName- name of the new elementaValue- text content of the new element- Returns:
- the new element
-
getOrCreateChild
public static org.jdom2.Element getOrCreateChild(org.jdom2.Element aParentElement, String aChildName) Returns the child element of aParentElement with the given name. If it does not exist, it is created (in the namespace of the parent) and attached to aParentElement.- Parameters:
aParentElement- parent elementaChildName- name of the child- Returns:
- the existing or new child element
-
addTextToChildThatMayExist
public static void addTextToChildThatMayExist(org.jdom2.Element aParentElement, String aChildName, String aValue) Appends text to the child of aParentElement with the name aChildName. If the child does not exist, it is created and attached.- Parameters:
aParentElement- parent elementaChildName- name of the childaValue- text to append
-
getElementFromStream
public org.jdom2.Element getElementFromStream(InputStream tFileIn) throws org.jdom2.JDOMException, IOException Parses an XML stream and returns its root element. The stream is not closed.- Parameters:
tFileIn- stream to parse- Returns:
- the root element
- Throws:
org.jdom2.JDOMException- if the content is not well-formed XMLIOException- if reading fails
-
getDocumentFromStream
public org.jdom2.Document getDocumentFromStream(InputStream tFileIn) throws org.jdom2.JDOMException, IOException Parses an XML stream and returns the document. The stream is not closed.- Parameters:
tFileIn- stream to parse- Returns:
- the document
- Throws:
org.jdom2.JDOMException- if the content is not well-formed XMLIOException- if reading fails
-
getDocumentFromString
public org.jdom2.Document getDocumentFromString(String aString) throws org.jdom2.JDOMException, IOException Parses an XML string and returns the document.- Parameters:
aString- XML document as string- Returns:
- the document
- Throws:
org.jdom2.JDOMException- if the string is not well-formed XMLIOException- if reading fails
-
getElementFromReader
public org.jdom2.Element getElementFromReader(Reader aReader) throws org.jdom2.JDOMException, IOException Parses XML from a reader and returns its root element. The reader is not closed.- Parameters:
aReader- reader to parse- Returns:
- the root element
- Throws:
org.jdom2.JDOMException- if the content is not well-formed XMLIOException- if reading fails
-
getElementFromFile
Parses an XML file and returns its root element. Files ending with.gzare decompressed. If the file does not exist, a resource with the same file name (plain or GZIP compressed) is looked up on the class path. Errors are logged.- Parameters:
aFile- XML file to parse- Returns:
- the root element, or
nullif an error occurred
-
getElementFromFile
Parses an XML file with the given character encoding and returns its root element. Files ending with.gzare decompressed. If the file does not exist, a resource with the same file name (plain or GZIP compressed) is looked up on the class path. Errors are logged.- Parameters:
aFile- XML file to parseaEncoding- character encoding of the file, e.g.UTF-8- Returns:
- the root element, or
nullif an error occurred
-
getAttributeValueOrEmptyString
public static final String getAttributeValueOrEmptyString(org.jdom2.Element aElement, String aAtrributeValue) Returns the value of an attribute, or an empty string if it does not exist.- Parameters:
aElement- element to read fromaAtrributeValue- name of the attribute- Returns:
- the attribute value, or
""if it does not exist
-
getAttributeValueOrNull
public static final String getAttributeValueOrNull(org.jdom2.Element aElement, String aAtrributeValue) Returns the value of an attribute, ornullif it does not exist or is empty.- Parameters:
aElement- element to read fromaAtrributeValue- name of the attribute- Returns:
- the attribute value, or
nullif it does not exist or is empty
-
getBooleanAttributeValue
public static final boolean getBooleanAttributeValue(org.jdom2.Element aElement, String aName, boolean aDefault) Returns the value of an attribute as boolean. Only the exact valuetrueis interpreted astrue.- Parameters:
aElement- element to read fromaName- name of the attributeaDefault- value to return if the attribute does not exist- Returns:
- the attribute value as boolean, or aDefault if it does not exist
-
getNumberAttributeValue
public static <T extends Number> T getNumberAttributeValue(org.jdom2.Element aElement, String aAttr, Class<T> aNumberType, T aDefault) Returns the value of an attribute converted to a number type. A warning is logged if the value cannot be converted.- Type Parameters:
T- number type- Parameters:
aElement- element to read fromaAttr- name of the attributeaNumberType- number type the value is converted to (subclass ofNumber)aDefault- value returned if the attribute does not exist, is empty or cannot be converted toaNumberType- Returns:
- the attribute value as number, or aDefault
-
isXMLWellFormed
Checks whether a string is well-formed XML.- Parameters:
aXMLString- string to check- Returns:
trueif the string can be parsed
-
transformElementToMap
Transforms theparameterchildren of an element into a map from theirkeyattribute to their text. If a parameter has no text but aresultchild, the serialisedresultelement is used as value. Expected structure:<root> <parameter key="key1">value1</parameter> <parameter key="key2">value2</parameter> </root>
- Parameters:
aElement- the root element; may benull- Returns:
- map from key to value; empty if aElement is
null - See Also:
-
createParameterElement
-
createTextElement
public static org.jdom2.Element createTextElement(String aId, String aTitle, String aRequired, String aEnabled, String aDefault) Creates a form field element<text>.- Parameters:
aId- value of theidattributeaTitle- value of thetitleattribute; omitted if emptyaRequired- value of therequiredattribute; omitted if emptyaEnabled- value of theenabledattribute; omitted if emptyaDefault- value of thedefaultattribute; omitted if empty- Returns:
- the new element
- See Also:
-
createChoiceElement
public static org.jdom2.Element createChoiceElement(String aId, String aTitle, String aRequired, String aEnabled, String aType, String aLocalize, String aMultiselect, String aDefault, Map<String, String> aOptions) Creates a form field element<choice>with<option>children.- Parameters:
aId- value of theidattributeaTitle- value of thetitleattribute; omitted if emptyaRequired- value of therequiredattribute; omitted if emptyaEnabled- value of theenabledattribute; omitted if emptyaType- value of thetypeattribute; omitted if emptyaLocalize- value of thelocalizeattribute; omitted if emptyaMultiselect- value of themultiselectattributeaDefault- value of thedefaultattribute; omitted if emptyaOptions- options as map from display text to option id- Returns:
- the new element
-
createDoubleElement
public static org.jdom2.Element createDoubleElement(String aId, String aTitle, String aRequired, String aEnabled, String aMin, String aMax, String aType, String aDefault) Creates a form field element<double>.- Parameters:
aId- value of theidattributeaTitle- value of thetitleattribute; omitted if emptyaRequired- value of therequiredattribute; omitted if emptyaEnabled- value of theenabledattribute; omitted if emptyaMin- value of theminattributeaMax- value of themaxattributeaType- value of thetypeattribute; omitted if emptyaDefault- value of thedefaultattribute; omitted if empty- Returns:
- the new element
-
createIntegerElement
public static org.jdom2.Element createIntegerElement(String aId, String aTitle, String aRequired, String aEnabled, String aMin, String aMax, String aType, String aDefault) Creates a form field element<integer>.- Parameters:
aId- value of theidattributeaTitle- value of thetitleattribute; omitted if emptyaRequired- value of therequiredattribute; omitted if emptyaEnabled- value of theenabledattribute; omitted if emptyaMin- value of theminattributeaMax- value of themaxattributeaType- value of thetypeattribute; omitted if emptyaDefault- value of thedefaultattribute; omitted if empty- Returns:
- the new element
-
createFieldElement
public static org.jdom2.Element createFieldElement(String aName, String aTitle, String aId, String aRequired, String aEnabled, String aDefault) Creates a form field element with the common attributes.- Parameters:
aName- element name, i.e. the field type (e.g.text,integer)aTitle- value of thetitleattribute; omitted if emptyaId- value of theidattributeaRequired- value of therequiredattribute; omitted if emptyaEnabled- value of theenabledattribute; omitted if emptyaDefault- value of thedefaultattribute; omitted if empty- Returns:
- the new element
-
evaluateXPath
Evaluates an XPath expression on a document and returns the matching elements. The namespace of the root element is available in the expression. Errors are logged.- Parameters:
aDoc- document to queryaExpression- XPath expression- Returns:
- the matching elements, or
nullif an error occurred
-
evaluateXPath
Evaluates an XPath expression relative to an element and returns the matching elements. The namespace of the element is available in the expression. Errors are logged.- Parameters:
aElement- context elementaExpression- XPath expression- Returns:
- the matching elements, or
nullif an error occurred
-
selectSingleElement
public static org.jdom2.Element selectSingleElement(Object aContext, String aExpression) throws org.jdom2.JDOMException Returns the first element selected by an XPath expression (replaces the deprecatedorg.jdom2.xpath.XPath.selectSingleNode). Expressions starting with//search the whole document of the context.- Parameters:
aContext- context node, e.g. an element or a documentaExpression- XPath expression selecting elements- Returns:
- the first selected element, or
nullif there is none - Throws:
org.jdom2.JDOMException- if the expression is invalid or cannot be evaluated
-
evaluateXPathSingleResult
Evaluates an XPath expression on a document and returns the first result as string. For text nodes and elements the trimmed text is returned, for other results (e.g. attributes, numbers) theirtoString(). Errors are logged.- Parameters:
aDoc- document to queryaExpression- XPath expression- Returns:
- the first result as string, or
nullif there is no result or an error occurred
-
transformMapToElement
public static org.jdom2.Element transformMapToElement(Map<String, Object> aParameterMap, String aNameOfRootElement) Transforms a map into an element with oneparameterchild per entry.- Parameters:
aParameterMap- map from key to valueaNameOfRootElement- name of the element to create- Returns:
- the new element
- See Also:
-
checkAttributeExists
Checks whether an element has an attribute.- Parameters:
aVarElement- element to checkaString- name of the attribute- Returns:
trueif the attribute exists
-
checkAttributeNotEmpty
Checks whether an element has an attribute with a non-blank value.- Parameters:
aVarElement- element to checkaString- name of the attribute- Returns:
trueif the attribute exists and is not empty or whitespace only
-
checkValueExists
public static boolean checkValueExists(org.jdom2.Element aVarElement) Checks whether an element has non-blank text content.- Parameters:
aVarElement- element to check- Returns:
trueif the trimmed text is not empty
-
toIntArray
-
toDoubleArray
-
toDoubleMatrix
-
generateProjectXML
public static org.jdom2.Document generateProjectXML(String aProjectDataFile, List<FWSimVariable<?>> aVars, Map<FWSimVariable<?>, String> aSensitivityVarsMap, org.jdom2.Element aOutputsElement) throws org.jdom2.JDOMException, IOException Generates a project XML document that reads the project data from a CSV file. If sensitivity variables are given, anEquidistantCalSimGenerator, a CSV outputSensitivityOut(file${_OUTPUTDIR_}/Cal_Out.csv) and the corresponding interface are added.- Parameters:
aProjectDataFile- path of the CSV file with the project dataaVars- variables added as columns to the project resource headeraSensitivityVarsMap- variables to vary, mapped to their values: for DOUBLE and INT variablesmin,max,count, for other types the value list; may benullaOutputsElement- existingoutputselement to add the sensitivity output to; ifnull, a new one is created- Returns:
- the project document
- Throws:
org.jdom2.JDOMException- if the internal template cannot be parsedIOException- if the internal template cannot be read
-
toStringArray
-