Java using a parsed xml in different classes - java

I was wondering how I can pass a parsed xml in different java classes within the same project. For example, I have
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder = factory. newDocumentBuilder();
Document document = builder.parse("Companies.xml");
etc.
And I can parse through it and do what I need to do in main, but I would like to be able to split up this process into different classes. I would have a class for employees, departments, etc. But when I do this in main I can simply say,
NodeList EmployeeList = document.getElementsByTagName("employees");. But if I were to try this in a different class it wouldnt have access to document. So how can I use the document in a different class, or do I have to create a new "document" file in every class? Thanks!

You would pass in the Document object to the constructor of the new class. Then it can parse the elements it needs.
Alternatively you could use a Java Object parser that can convert to and from XML for you.
Simple XML

Best would be
1.) To have a constructor in each class, accepting the Document Object as argument.
2.) Use the Document Object in other classes to get the values.
3.) Or you can directly convert from XML to JAVA Object or Java Object to XML, follow these links.
link1 and link2

Related

XML input/output with Java fitnesse

There is a .net version of this question answered here: XML input/output with Fitnesse
I need to do that with the Java version of Fitnesse and there doesn't seem to be anything similar. I have some tests that accept XML and return XML so I need both the input and the expected output to handle XML in the fields. I've tried various html escaping, but that doesn't seem to get the job done on the comparison side of things. The XML is arbitrary, so I can't parse it into domain objects and compare individual fields (well, I could, but there'd be tons of different object mappings).
Anyone find a way to deal with this issue in a generic way? A custom Java equivalent of the .net solution that exists somewhere?
Not sure if this is best solution. You may want to use some XML frameworks e.g. XStream which has very simple API to convert XML into JAVA objects. Using this, you may want to convert both XML files in JAVA and use JAVA comparison.
Simple steps would be:
Define simple Java object (POJO) e.g. MyXMLObj to map the XML attributes in Java attributes.
Create/generate equals method in the above POJO class MyXMLObj.
Convert your XMLs in Java as :
XStream xstream = new XStream();
XStream xstream = new XStream(new DomDriver());
//or
//XStream xstream = new XStream(new StaxDriver());
MyXMLObj myXMLObj1= (MyXMLObj)xstream.fromXML(xml1);
MyXMLObj myXMLObj2= (MyXMLObj)xstream.fromXML(xml2);
Simply compare the two objects as:
if(myXMLObj1.equals(myXMLObj2)){
System.out.println("Matching");
}else{
System.out.println("Not Matching");
}
I encountered something similar where xml response could change in future or doesn't confirm to a particular style all the time, or xml is not returned as an xml object rather a string is returned etc.
I wrote a generic fixture that would take an xml string and parse it to give us an xml doc object. I would also capture the xml element path and expected value from the wiki and I confirm if expected value is what is stored in the xml or not using xpath.
!|ValidateXmlValue |
|xmlString|xmlElem |getXMLvalue? |
|$respBody|/root/childnode1/ |${variable} |
This way users have the flexibility to query node value by simply giving the full path to that node and compare it against an input variable etc. Even if something changes, only test will need to change (you can store path to each xml element in a variable as well, as part of set-up step)

JAXB and document object

I am getting object of type org.w3c.dom.Document from a source (basically a parsed xml document - java object). I want to use this xml document object to create java objects using JAXB. How can I do that?
You can unmarshal directly from DOM objects, this includes a org.w3c.dom.Document:
http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/Unmarshaller.html#unmarshal%28org.w3c.dom.Node%29
If you need to specify the type of object you are unmarshalling, then you can wrap the DOM node in a javax.xml.transform.dom.DOMSource and use the following API:
http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/Unmarshaller.html#unmarshal%28javax.xml.transform.Source,%20java.lang.Class%29
From the top of my head you could just convert the Document to a Stream and use the Unmarshaller to convert to the JAXB instance you need.
Something like:
MyJAXB o = (MyJAXB)unmarshaller.unmarshall(new StringReader(arrayoutsream.tostring()));
Disclaimer: Haven't even bothered to see if this compiles but you should understand how to approach this

How to use getDocumentElement in user-defined class?

I am implementing a class that reads XML files and calls methods related to the tags. I have coded this in C++ and all I had to do was inherit something like wxXmlDocument inorder to get the root of my Xml.
I want to do this in Java, and the class that can get me the root element is the interface Document. I want to be able to call getDocumentElement() without having to implement it. Can anyone tell me how?
Thanks. :)
This is the simplest example of using the built-in DOM parser:
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final Document doc = db.parse(new File(filename));
Note that the DOM version of parsing will load the entire document into memory. If you are dealing with very large documents (compared to main heap available) you will likely want to learn how to use the SAX or STAX versions of parsing.

XML formatted Java string manipulation

I'm developing a plugin that has node(computer) objects with attributes like:
String name
String description
String labels
Launcher computerLauncher
...
I can convert the node(computer) object to an XML-formated String like:
String xml = jenkins.instance.toXML(node);
Which gives me a string:
<name>Computer1</name>
<description>This is a description</description>
<labels>label1 label2</labels>
<launcher>windows.object.launcher.12da1</launcher>
Then I can go the other way back:
Node node = jenkins.instance.fromXML(xml);
I have no methods for changing attributes in a Node so I want to convert it to XML, change som attributes and then make it a Node again.
I see two options
Manipulate the XML with some String methods to replace everything in between the <> tags.
Try to cast the XML string to something like a real Object and manipulate it that way.
Not sure what would be the best approach.
Why invent something new when there already is support for all that using Java's DOM (Document Object Model) API?
Use a DocumentBuilderFactory to get a DocumentBuilder and create a Document instance. With this you can create the 'Node' objects (please note that the example you posted is actually not valid XML, it's missing a root node) in your toXML method, serializing the Document to a String could be done by using a Transformer.
With the DOM API you can also modify the attributes of your existing elements.
Parsing the Document instance from an XML string is realized again with the help of the DocumentBuilder, using DocumentBuilder#parse.
If your DOM operations are not too complex this should be a nice, quick way to accomplish your goal.
It makes sense to me to use a DOM-like approach. But don't use DOM itself: there are much better alternatives like JDOM and XOM that have much friendlier APIs.
recenty I had to manipulate large XML files (my software had to create some XML files dynamically and get input data from some other XML files). To do this I've used JAXB, which is a very neat API that marshalls XML files into Java objects and Java objects into XML files automatically.
However to do this I had to create a XSD file to specify the XMLs that I would need to read and write from.
Therefore JAXB requires more work to set up than DOM, so if your needs are simple I suggest that you use DOM, however if your needs are more complex, then I would suggest JAXB.

String of KML needs to be converted to java objects

I have a string of kml coming in on a request object. I have used xjc to create the kml java objects. I am looking for an easy way to create the kml nested java objects from this string. I could parse the string and create each object in the tree by hand but wouldn't it be cool if there was a library or something that would create the java objects for me? Something like KmlType type = parseKML(mykmlStringFromTheRequest); Then type would be a Tree of kml objects. Thanks for the help all.
JAK http://labs.micromata.de/display/jak/Home will help

Categories