Exception while parsing string to document object - java

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);

Related

Converting XML to document in java creates null document

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.

Parsing a SOAP response is returning null

String response = "<?xml version='1.0'?><soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope'><soap:Body><exch:Response xmlns:exch='http://applicant.ffe.org/exchange/1.0'>...</exch:Response></soap:Body></soap:Envelope>";
DocumentBuilderFactory dbf = null;
DocumentBuilder db = null;
org.w3c.dom.Document document = null;
try {
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new ByteArrayInputStream(response.getBytes("UTF-8")));
document = db.parse(is);
} catch(ParserConfigurationException e){}
catch(SAXException e){}
document is returning with null. I have tried different ways to pass to InputSource, but document is still returning null. Any idea why this might be happening?
I just tried i could get the elements name and values .
try {
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new ByteArrayInputStream(response.getBytes("UTF-8")));
document = db.parse(is);
System.out.println(document);//here we get null;
System.out.println(document.getNodeName());//here we get document;
for(int i =0 ; i<document.getChildNodes().getLength();i++)
System.out.println(document.getChildNodes().item(i).getChildNodes().item(i).getNodeName());
}
Output :
[#document: null]
document
soap:Body
To parse SOAPResponse we can javax.xml.soap.* it may take u to traverse the object xml tree. Anyway we may need parse the elements from SOAP Body . we could parse these very simple manner using DOM format .

How to convert String to DOM Document object in java?

I have a case like getting an XML and convert the XML elements to document object and getting the element values and attributes which i have been created already
Here is the piece of code i have tried to convert the string to DOM document object
String xmlString = " <r><e>d</e></r>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(new InputSource(new StringReader(xmlString)));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
String str1 = result.getWriter().toString();
System.out.println(str1);
But this case is valid for only elements without attributes
what can we do if the
String xmlString = "<element attribname="value" attribname1="value1"> pcdata</element>"
we are using Double quotes for the attribute values"value". The compiler is showing error
Suggest me if there any xml encoder and decoder is there to handle this scenarios ??
you can try
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));
Document doc = db.parse(is);
refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm
Either escape the double quotes with \
String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"
or use single quotes instead
String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
this works well for me even though the XML structure is complex.
And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.
The main problem might not come from the attributes.
public static void main(String[] args) {
final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
"<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
"<role>Developer</role><gen>Male</gen></Emp>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) );
} catch (Exception e) {
e.printStackTrace();
}
}

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);
}

org.apache.xerces.dom.DeferredDocumentImpl incompatible with org.dom4j.Document

Im reading some RSS from an URL and are experiencing some troubles.
Initially I had a straightforward implementation like this:
SAXReader reader = new SAXReader();
Document doc = reader.read(new URL(sURL));
However, this didnt allow me to timeout the request if the response was very slow. So I changed it to :
public static org.dom4j.Document readXml(InputStream is) throws SAXException, IOException,
ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db = null;
db = dbf.newDocumentBuilder();
return (org.dom4j.Document)db.parse(is);
}
SAXReader reader = new SAXReader();
URL myUrl = new URL(sURL);
URLConnection c = myUrl.openConnection();
c.setConnectTimeout(10000);
c.setReadTimeout(10000);
org.dom4j.Document doc = readXml(c.getInputStream());
Element root = doc.getRootElement();
When trying this, I get a annyoing error:
org.apache.xerces.dom.DeferredDocumentImpl incompatible with org.dom4j.Document
How can I avoid this? None of the above methods are supposed to return that type of Document, and I also try to cast to the correct document type..
EDIT: The problem is db.parse(is) which returns org.w3c.dom ..
Make sure your Element is of type org.dom4j.Element and not org.w3c.dom, javax.bind.xml, etc.
In other words, dom4j API is not compatible with Java's built-in XML API. The two simply do not mix together, unless you operate with Strings (e.g. generate XML in dom4j and parse it with Java's XML or vice versa).
Problem solved!
By using :
DOMReader domReader = new DOMReader();
org.dom4j.Document dom4jDoc = domReader.read(doc);
org.dom4j.Element root = (Element)dom4jDoc.getRootElement();
To create an org.dom4j.Document from the org.w3c.dom.Document

Categories

Resources