Use XmlWorker and XmlNode

If you work with XML files, it's not too easy to use the right parser because there are many of them and, if you want a simple parser without writing a lot of source code, you need some luck.

We added two classes to JVx that solves simple XML handling.


XML file:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Before begin! -->
  <!-- Test: STARTPORT -->
  <!-- Test: TCP information 
      second row
      third row
 after an empty row
  <report name="Standard">
  <report name="User">
  <text>This is a text
from Hansi Huber
<!--  After End -->

Read/Insert/Set tags:

XmlWorker xmw = new XmlWorker();
XmlNode xmn ="simple.xml");
// Read nodes
//Access a single TAG
//Access a TAG from a list
// Insert new nodes
//quick inserts
xmn.insertNode("/server/report(0)", null);
xmn.setNode("/server/report(0)/format", "ABC");
xmn.insertNode("/server/startport(1)", "ABCD");
//with nodes
XmlNode xmnInsert = new XmlNode("ABCD");
xmnInsAttrib  = new XmlNode(XmlNode.TYPE_ATTRIBUTE, "attrib1", xmnInsert);
xmn.insertNode("/server/startport(1)", xmnInsert);
// Set nodes
xmn.setNode("/server/domain", "")
// Save
xmn.write("simple_new.xml", xmn);

It's easy to access and modify information in an XML file. We use '/' as separator for navigating through the hierarchy and (n) to access tags from a list of tags.

There are more useful methods, e.g., find the index of a tag in a list of tags. The following example creates a XML structure in memory.

XmlNode xmn = XmlNode.createXmlDeclaration();
xmn.insertNode("/server/a/b/c", "A");
xmn.insertNode("/server/a/b/c", "B");
xmn.insertNode("/server/a/b/c", "A");
xmn.insertNode("/server/a/b/c", "B");
xmn.insertNode("/server/a/b/c", "A");
xmn.insertNode("/server/a/b(1)/c", "A");
xmn.insertNode("/server/a/b/b", "A");
XmlNode xmnSearch = xmnRead.getNode("/server/a/b(0)"); 
//returns 0
xmnSearch.indexOf("/c", "A", 0);
//returns 2
xmnSearch.indexOf("/c", "A", 1);
//returns 3
xmnSearch.indexOf("/c", "A", 3);
//returns 0
xmnSearch.indexOf("/b", "A", 0);
xmn.insertNode("/server/a/b(1)/1", "A");
xmn.insertNode("/server/a/b(2)/2", "A");
xmn.insertNode("/server/a(1)/b/3", "A");
//returns 0
xmn.indexOf("/server/a/b/b", "A", 0)

The <XmlNode>.toString() method returns the XML representation of the node and all subnodes.

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information