Converting XML to document in java creates null document - java

I'm trying to parse xml, downloaded from the web, in java, following examples from here (stackoverflow) and other sources.
First I pack the xml in a string:
String xml = getXML(url, logger);
If I printout the xml string at this point:
System.out.println("XML " + xml);
I get a printout of the xml so I'm assuming there is no fault up to this point.
Then I try to create a document that I can evaluate:
InputSource is= new InputSource(new StringReader(xml));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
If I print out the document here:
System.out.println("Doc: " + doc);
I get:
Doc: [#document: null]
When I later try to evaluate expressions with Xpath I get java.lang.NullPointerException and also when just trying to get the length of the root:
System.out.println("Root length " + rootNode.getLength());
which leaves me to believe the document (and later the node) is truly null.
When I try to print out the Input Source or the Node I get eg.
Input Source: org.xml.sax.InputSource#29453f44
which I don't know how to interpret.
Can any one see what I've done wrong or suggest a way forward?
Thanks in advance.

You may need another way to render the document as a string.
For JDOM:
public static String toString(final Document document) {
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
final XMLOutputter outp = new XMLOutputter();
outp.output(document, out);
final String string = out.toString("UTF-8");
return string;
}
catch (final Exception e) {
throw new IllegalStateException("Cannot stringify document.", e);
}
}
The output
org.xml.sax.InputSource#29453f44
simply is the class name + the hash code of the instance (as defined in the Object class). It indicates that the class of the instance has toString not overridden.

Related

How to use the return value of a java method in an XML

I have an xml like this
<step>
<navigationButtonSelector>.step-one-action-button</navigationButtonSelector>
<formField>
<name>emailAddress</name>
<value>new2#gmail.com</value>
</formField>
</step>
Now I can't hardcode the value (new2#gmail.com) here. Instead I have to randomly generate a string and use it whenever I am running my automation suite. Can I generate a random string at runtime within the xml itself.
The other possibility is to create a Java method which returns a random String. Now how could I use that value in my XML file? Please help
This code may look bloated but actually is very powerful in case you have to perform more editing. It shows the whole roundtrip from parsing, modifying and serializing the XML data from and to String.
String xml = "<step>\n" +
" <navigationButtonSelector>.step-one-action-button</navigationButtonSelector>\n" +
" <formField>\n" +
" <name>emailAddress</name>\n" +
" <value>new2#gmail.com</value>\n" +
" </formField>\n" +
"</step>";
// parse document
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xml)));
// find editing locatioin
XPath xpath = XPathFactory.newInstance().newXPath();
Element value = (Element)xpath.evaluate("/step/formField/value", doc, XPathConstants.NODE);
// replace value
while (value.hasChildNodes()) {
value.removeChild(value.getFirstChild());
}
value.appendChild(doc.createTextNode("a random string"));
// serialize document
StringWriter sw = new StringWriter();
Transformer t = TransformerFactory.newDefaultInstance().newTransformer();
t.transform(new DOMSource(doc), new StreamResult(sw));
xml = sw.toString();
System.out.println(xml);

Exception while parsing string to document object

I try to bild document object from string and append it into element but I get exception java.io.FileNotFoundException: project folder path\org.xml.sax.InputSource in this line: Document constantDocument = docBuilder.parse(
String.valueOf(new InputSource( new StringReader( xmlAsString ) )));.
My code looks like this:
Element infoElement = document.createElement("information");
String xmlAsString = "..."; //xml in string format
Document constantDocument = docBuilder.parse(
String.valueOf(new InputSource( new StringReader( xmlAsString ) ))); //java.io.FileNotFoundException
infoElement.appendChild(constantDocument);
What am I missing?
Reason is given here in the Documentation :
public Document parse(String uri)
throws SAXException,
IOException
Parse the content of the given URI as an XML document and return a new
DOM Document object. An IllegalArgumentException is thrown if the URI
is null null.
You are providing a String, and Java is looking to fetch the file at the given String / URI and hence the Exception ...
Based on your attempt, the closest you could use is :
parse(InputSource is)
Parse the content of the given input source as
an XML document and return a new DOM Document object.
So changing the .parse to below should solve your problem :
Document constantDocument = docBuilder.parse(new InputSource(new StringReader(xmlAsString)));
Found what I was looking for:
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><nod1></node1></root>"));
Document doc = db.parse(is);

Cannot create XML Document from String

I am trying to create an org.w3c.dom.Document form an XML string. I am using this How to convert string to xml file in java as a basis. I am not getting an exception, the problem is that my document is always null. The XML is system generated and well formed. I wish to convert it to a Document object so that I can add new Nodes etc.
public static org.w3c.dom.Document stringToXML(String xmlSource) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream input = IOUtils.toInputStream(xmlSource); //uses Apache commons to obtain InputStream
BOMInputStream bomIn = new BOMInputStream(input); //create BOMInputStream from InputStream
InputSource is = new InputSource(bomIn); // InputSource with BOM removed
Document document = builder.parse(new InputSource(new StringReader(xmlSource)));
Document document2 = builder.parse(is);
System.out.println("Document=" + document.getDoctype()); // always null
System.out.println("Document2=" + document2.getDoctype()); // always null
return document;
}
I have tried these things: I created a BOMInputStream thinking that a BOM was causing the conversion to fail. I thought that this was my issue but passing the BOMInputStream to the InputSource doesn't make a difference. I have even tried passing a literal String of simple XML and nothing but null. The toString method returns [#document:null]
I am using Xpages, a JSF implementation that uses Java 6. Full name of Document class used to avoid confusion with Xpage related class of the same name.
Don't rely on what toString is telling you. It is providing diagnostic information that it thinks is useful about the current class, which is, in this case, nothing more then...
"["+getNodeName()+": "+getNodeValue()+"]";
Which isn't going to help you. Instead, you will need to try and transform the model back into a String, for example...
String text
= "<fruit>"
+ "<banana>yellow</banana>"
+ "<orange>orange</orange>"
+ "<pear>yellow</pear>"
+ "</fruit>";
InputStream is = null;
try {
is = new ByteArrayInputStream(text.getBytes());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
System.out.println("Document=" + document.toString()); // always null
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
ByteArrayOutputStream os = null;
try {
os = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(document);
StreamResult sr = new StreamResult(os);
tf.transform(domSource, sr);
System.out.println(new String(os.toByteArray()));
} finally {
try {
os.close();
} finally {
}
}
} catch (ParserConfigurationException | SAXException | IOException | TransformerConfigurationException exp) {
exp.printStackTrace();
} catch (TransformerException exp) {
exp.printStackTrace();
} finally {
try {
is.close();
} catch (Exception e) {
}
}
Which outputs...
Document=[#document: null]
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<fruit>
<banana>yellow</banana>
<orange>orange</orange>
<pear>yellow</pear>
</fruit>
You can try using this: http://www.wissel.net/blog/downloads/SHWL-8MRM36/$File/SimpleXMLDoc.java

Parsing CDATA content from webservice response in Java

I'm making a webservice call in my Java code and getting the response as String with the below data.
<DocumentElement>
<ResultSet>
<Response>Successfully Sent.</Response>
<UsedCredits>1</UsedCredits>
</ResultSet>
</DocumentElement>
Now, I want to parse the below response String and get the value of <Response> tag alone for further processing. Since, I'm getting only the CDATA content how to parse the String content?
You obviously need XML parser for this one. Lets say the above is stored in a String variable named content
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(content)); //content variable holding xml records
Document doc = db.parse(is)
/* Now retrieve data from xml */
NodeList nodes = doc.getElementsByTagName("ResultSet");
Element elm = (Element) nodes.item(0); //will get you <Response> Successfully Sent.</Response>
String responseText = elm.getFirstChild().getNodeValue();
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
Follow the above parser routine for larger data sets. Use loops for multiple similar data sets. Hope that helps.

How to create a XML object from String in Java?

I am trying to write a code that helps me to create a XML object. For example, I will give a string as input to a function and it will return me a XMLObject.
XMLObject convertToXML(String s) {}
When I was searching on the net, generally I saw examples about creating XML documents. So all the things I saw about creating an XML and write on to a file and create the file. But I have done something like that:
Document document = new Document();
Element child = new Element("snmp");
child.addContent(new Element("snmpType").setText("snmpget"));
child.addContent(new Element("IpAdress").setText("127.0.0.1"));
child.addContent(new Element("OID").setText("1.3.6.1.2.1.1.3.0"));
document.setContent(child);
Do you think it is enough to create an XML object? and also can you please help me how to get data from XML? For example, how can I get the IpAdressfrom that XML?
Thank you all a lot
EDIT 1: Actually now I thought that maybe it would be much easier for me to have a file like base.xml, I will write all basic things into that for example:
<snmp>
<snmpType><snmpType>
<OID></OID>
</snmp>
and then use this file to create a XML object. What do you think about that?
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
You can use the document object and xml parsing libraries or xpath to get back the ip address.
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}

Categories

Resources