A Java library to easily parse, unparse and manipulate XML.
- Release notes
- Introduction
- Setup
- Documentation
- XMLElement
- XMLElement(String tagName)
- String getTagName()
- String getTextContent()
- void setTextContent(String content)
- void appendTextContent(String content)
- void addAttribute(String name, String value)
- String getAttribute(String name)
- boolean hasAttribute(String name)
- String removeAttributeByName(String name)
- HashMap<String, String> getAllAttributes()
- Iterator<Map.Entry<String, String>> getAttributesIterator()
- void addChild(XMLElement child)
- void addChild(int i, XMLElement child)
- void removeChild(XMLElement child)
- void removeChild(int i)
- XMLElement getChildAt(int i)
- int indexOfChild(XMLElement child)
- int getNumberOfChildren()
- ArrayList<XMLElement> getAllChildren()
- Iterator<XMLElement> getChildrenIterator()
- void swapChildrenPosition(int i, int j)
- void moveChildPositionUp(int i, int n)
- void moveChildPositionDown(int i, int n)
- ArrayList<XMLElement> getDescendantsWithTag(String tagName)
- String toString()
- String toString(String tabulationCharacters)
- Object clone()
- XMLTreeBuilder
- XMLElement
- Example
- Conclusion
- 1.0.1: Renamed package: "it.trv.easyxml" -> "it.trvi.easyxml"
- 1.0.0: Initial release
The scope of this library is to provide an instrument to easily parse, unparse and manipulate XML code. Unlike other Java libraries that focus mostly on high speed parsing, this library focuses on ease of use and maximum flexibility. This library is thus ideal for projects that don't need extremely high performance XML parsing, but instead need a simple and ready-to-use parser of XML and/or the ability to freely inspect and manipulate XML items.
The parser in this library is based on the Java DOM parser.
All the classes in this library are contained in the package "it.trvi.easyxml
".
You can download the jar file containing the most recent recent version of this library from the releases page on Github.
This library is composed by two classes: XMLElement
represents a single XML element and provides methods to access and modify its data and its children; XMLTreeBuilder
provides various functions to parse XML code into an XMLElement.
Both these classes are contained in the package "it.trvi.easyxml
".
The XMLElement class represents an XML element with its text content, attributes and children. The tag name is immutable and is set at the moment of the object initialization, all the other features can be modified.
XMLElement implements Cloneable.
Constructor for an XMLElement. It takes the tag name, which is immutable.
Parameters:
tagName
is the tag name.
Returns the tag name of this XMLElement.
Returns:
the tag name of this XMLElement
Returns the text content of this XMLElement.
Returns:
the text content of this XMLElement
Replaces the text content of this XMLElement with the string passed as input.
Parameters:
content
is the new text content of this XMLElement
Appends the string passed as input to the text content of this XMLElement.
Parameters:
content
is the new text that must be appended
Adds to this XMLElement a new attribute by specifying its name and value. If an attribute with the same name already exists, it is replaced.
Parameters:
name
is the name of the attribute that must be added
value
is the value of the attribute that must be added
Returns the value of the attribute that has a specific name.
Parameters:
name
is the name of the attribute whose value must be returned
Returns:
the value of the attribute with that specific name
Throws:
NoSuchElementException
if this XMLElement has no attribute with that name
Returns true if this instance of XMLElement has a specific attribute.
Parameters:
name
is the name of the attribute
Returns:
true if this instance of XMLElement has an attribute named name
, false otherwise
Removes a specific attribute from this XMLElement and returns the value of that attribute. If that attribute does not exist, it returns null.
Parameters:
name
is the name of the attribute that must be removed
Returns:
the value of the attribute that is removed, null if the attribute was not present
Returns a HashMap that contains all the attributes of this instance of XMLElement.
Returns:
a HashMap<String, String> containing all the attributes of this XMLElement
Returns a fail-fast Iterator that iterates over all the attributes of this instance of XMLElement.
Returns:
an Iterator<Map.Entry<String, String>> that iterates over all the attributes of this XMLElement
Adds an XMLElement to the children of this XMLElement.
Parameters:
child
is the XMLElement that must be added to the children of this XMLElement
Throws:
IllegalArgumentException
if child
is an ancestor of this XMLElement or if this
and child
are the same object
Adds an XMLElement to the children of this XMLElement at the specific position in the list of children.
Shifts the child currently at that position (if any) and any subsequent children to the right (adds one to their indices).
Parameters:
i
is the index at which the new child will be located
child
is the XMLElement that must be added to the children of this XMLElement
Throws:
IllegalArgumentException
if child is an ancestor of this XMLElement or if this and child are the same object
Removes an XMLElement from the children of this XMLElement. Only the direct children are removed, not the other descendants.
Parameters:
child
is the children that must be removed
Throws:
NoSuchElementException
if child
is not a child of this XMLElement.
Removes the child at the specified position from the list of children of this XMLElement.
Parameters:
i
is the index of the child that must be removed from the list of children of this XMLElement
Returns the child located at the specified position in the list of the children of this XMLElement.
Parameters:
i
is the index of the child in the list of the children of this XMLElement.
Returns:
the ith child of this XMLElement
Returns the index of the first occurrence of the specified XMLElement in the list of children of this XMLElement.
Parameters:
child
is the child whose index must be returned
Returns:
the index of the first occurrence of child
in the list of children of this XMLElement
Throws:
NoSuchElementException
if the specified element is not a child of this XMLElement.
Returns the number of direct children of this instance of XMLElement.
Returns:
the number of children of this instance of XMLElement
Returns an ArrayList that contains all the children of this instance of XMLElement.
Returns:
an ArrayList<XMLElement> containing all the children of this XMLElement
Returns a fail-fast Iterator that iterates over all the children of this instance of XMLElement.
Returns:
an Iterator<XMLElement> that iterates over all the children of this XMLElement
Swaps the positions of two children in the children list of this instance of XMLElement.
Parameters:
i
and j
are the indices of the two children that must be swapped
Moves a child in the children list of this instance of XMLElement "up" (that is, towards the beginning of the list) by a certain number of positions.
Parameters:
i
is the index of the child that must be moved
n
is the number of positions that the child at i must be moved up
Moves a child in the children list of this instance of XMLElement "down" (that is, towards the end of the list) by a certain number of positions.
Parameters:
i
is the index of the child that must be moved
n
is the number of positions that the child at i must be moved down
Returns the XML code corresponding to this XMLElement.
Returns:
the string representation of this XMLElement.
Returns all the descendants of this XMLElement that have a specific tag name.
Parameters:
tagName
is tag name of the descendants that must be returned
Returns:
an ArrayList<XMLElement> containing all the descendants of this XMLElement whose tag name is tagName
.
Returns the text corresponding to this XMLElement, with the possibility of choosing the tabulation.
Parameters:
tabulationCharacters
is the tabulation that will be used
Returns:
the string representation of this XMLElement.
Returns a deep copy of this XMLElement instance.
The XMLTreeBuilder class provides static methods to parse XML code into an XMLElement.
Static function that parses into an XMLElement the XML code contained in a string.
Parameters:
string
contains the XML code
Returns:
the parsed XMLElement containing the whole XML tree
Throws:
ParseException
if there's an error in the XML code
Static function that parses into an XMLElement the XML code contained in a file.
Parameters:
path
contains the path of the file
Returns:
the parsed XMLElement containing the whole XML tree
Throws:
ParseException
if there's an error in the XML code
FileNotFoundException
if the file in the specified path does not exist
Static function that parses into an XMLElement the XML code contained in a file.
Parameters:
file
is the file
Returns:
the parsed XMLElement containing the whole XML tree
Throws:
ParseException
if there's an error in the XML code
FileNotFoundException
if the file does not exist
Static function that parses into an XMLElement the XML code read from an InputStream.
Parameters:
stream
is the InputStream
Returns:
the parsed XMLElement containing the whole XML tree
Throws:
ParseException
if there's an error in the XML code
IOException
if there's an error while reading from the InputStream
In this example we suppose we have an XML file, "example.xml", that represents an email. This is its content:
<email>
<to>
<name>
Tom Bombadil
</name>
<address>
tomb@mail.me
</address>
</to>
<from>
<name>
Henry Walton Jones
</name>
<address>
henryjones@history.uchicago.edu
</address>
</from>
<body>
Hi,
you good?
</body>
</email>
In this example we will do the following:
- parse the file into an XMLElement
- print to screen all the names followed by their associated address
- append text to the body of the email
- change one email address
- create an "attachment" and add it to the file
- add a subject to the email
- print the modified XML data to a new file
//various imports...
public class EasyXMLExample{
public static void main(String[] args) throws FileNotFoundException, ParseException, UnsupportedEncodingException {
/*
First of all, we parse the XML file into an XMLElement. To do that, we need only the following line of code.
*/
XMLElement root = XMLTreeBuilder.buildFromFile("example.xml");
/*
Now we want to print all the names and relative addresses that appear in the file.
We use the function "getDescendantsWithTag" to extract from the file all the names and all the addresses.
Since the results of "getDescendantsWithTag" maintain the order that they have in the original XML code,
we can easily associate the names with their addresses.
*/
ArrayList<XMLElement> names = root.getDescendantsWithTag("name");
ArrayList<XMLElement> addresses = root.getDescendantsWithTag("address");
for(int i=0;i< names.size();i++){
System.out.println(names.get(i).getTextContent()+":\t"+addresses.get(i).getTextContent());
}
/*
Now we want to append some text to the body.
To access the body element, we use the fact that we know its position in the children of the root.
*/
root.getChildAt(2).appendTextContent("\nWhat did you have for dinner?");
/*
Let's pretend that Tom Bombadil's email address is wrong: how do we change it?
This time we access the address element using "getDescendantsWithTag" instead of its position.
We know that it's the second address in the document, and we exploit this fact.
*/
ArrayList<XMLElement> addresses2 = root.getDescendantsWithTag("address");
addresses2.get(1).setTextContent("tombombadil@mail.me");
/*
Now we want to create an "attachment" to add at the end of the document.
We create it from scratch and it has its own children and attributes.
*/
XMLElement attachment = new XMLElement("attachment");
attachment.addAttribute("size","4MB");
attachment.addAttribute("type","binary");
XMLElement name = new XMLElement("name");
name.setTextContent("important_document");
XMLElement content = new XMLElement("file_content");
content.setTextContent("010011100110111101110100001000000110000101101100011011000010000001110100011010000110111101110011011001010010000001110111011010000110111100100000011101110110000101101110011001000110010101110010001000000110000101110010011001010010000001101100011011110111001101110100");
attachment.addChild(name);
attachment.addChild(content);
root.addChild(attachment);
/*
We notice that this email is missing a subject.
We decide to create one and add it in the right place of the document, just before the body.
*/
XMLElement subject = new XMLElement("subject");
subject.setTextContent("About a peculiar neurosurgeon");
root.addChild(2,subject);
/*
The last thing we do is printing the modified XML code to a new file "out.xml".
*/
PrintWriter writer = new PrintWriter("out.xml", "UTF-8");
writer.print(root.toString());
writer.close();
}
}
After executing the previous code, this will be the content of "out.xml":
<email>
<to>
<name>
Tom Bombadil
</name>
<address>
tomb@mail.me
</address>
</to>
<from>
<name>
Henry Walton Jones
</name>
<address>
tombombadil@mail.me
</address>
</from>
<subject>
About a peculiar neurosurgeon
</subject>
<body>
Hi,
you good?
What did you have for dinner?
</body>
<attachment size="4MB" type="binary">
<name>
important_document
</name>
<file_content>
010011100110111101110100001000000110000101101100011011000010000001110100011010000110111101110011011001010010000001110111011010000110111100100000011101110110000101101110011001000110010101110010001000000110000101110010011001010010000001101100011011110111001101110100
</file_content>
</attachment>
</email>
This is everything you needed to know about the EasyXML library.
Please contact me if you find any bugs, errors in the documentation, missing features or have feedback or suggestions on how to improve the library.
If you are feeling generous, consider making a donation using one of the methods listed at the end of this document.
Stefano Travasci
Curecoin: BTLPs7AD8fhJpVbS1a4ddvC6JMqJxVTwip
Bitcoin: bc1qf79e5jxwgvpwm59yzw3ff0fsjh8r08h04luzwg
let me know if your favorite donation method is not in this list