I have to convert a GML-Server Response to a GPX-File with jdom in Java
So far the Get-Feature-Request i send to the server is correct and gives me a GML-File as response, but when i want to print the file it says [#document: null]
The output on console:
url https://www.geoportal-amt-beetzsee.de/isk/beet_radwanderwege?service=WFS&version=1.0.0&REQUEST=GetFeature&typename=Riewend-Burgwall-Wanderweg
[#document: null]
try {
//zu Funktionstestzwecken - löschen wenn nicht mehr benötigt
String typename = gui.ConverterDialog.tfconverter.getText();
String urlString = gui.UrlDialog.txturlinput.getText() + "?service=WFS&version=1.0.0&REQUEST=GetFeature&typename=" + typename;
//entfernen wenn nicht mehr benötigt
System.out.println("url "+ urlString);
URL url = new URL(urlString);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(url.openStream());
//doc.getDocumentElement().normalize();
//entfernen wenn nicht mehr benötigt
//doc null ???
System.out.println(doc);
} catch(Exception e) {
String errorMessage = "An error occured:" + e;
System.err.println(errorMessage);
e.printStackTrace();
}
When the line
System.out.println(doc);
runs, it calls the toString() method of the document doc and prints out that. The toString() method of the document doesn't serialize the XML document to a string; instead it just prints the node name and its value. The name of the document node is #document, and document nodes don't have values, so null gets printed instead.
I tried running your XML parsing code on a test XML document and it also printed out [#document: null].
It might look like your XML parsing has failed and left you with an empty document, but I don't believe that to be the case. Your code is quite probably working correctly.
If you want to serialize an XML document to a string, see this question.
This Code solved the issue:
//...
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(url.openStream());
doc.getDocumentElement().normalize();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
Related
I want to extract code and text separately from the soap fault listed below. The code that I am using (listed below xml) is printing code and text together.
<env:Fault xmlns:env = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:fault = "http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>fault:Client</faultcode>
<faultstring>An error occurred. Please check the detail section.</faultstring>
<detail>
<e:serviceFault xmlns:e = "http://xml.comcast.com/types">
<e:messages>
<e:message>
<e:code>ERRORCODE-82828</e:code>
<e:text>Error Message.</e:text>
</e:message>
</e:messages>
</e:serviceFault>
</detail>
</env:Fault>
Code
public void printSoapFaultClientException(SoapFaultClientException e) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
DOMResult result = new DOMResult();
transformer.transform(e.getSoapFault().getSource(), result);
NodeList nl = ((Document)result.getNode()).getElementsByTagName("detail");
System.out.println(" text content " + ((Element)nl.item(0)).getTextContent());
}
Here is an example of doing it , since it is a fault XML , i have just used a parser to parse the XML and extract a field off it. Also SOAPFaultClientException API's can help you extract the fault reason directly if you want it (http://docs.spring.io/spring-ws/site/apidocs/org/springframework/ws/soap/client/SoapFaultClientException.html)
File fXmlFile = new File("C:\\DevelopmentTools\\3.CODE\\SOAP.txt");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
XPath xpath = XPathFactory.newInstance().newXPath();
String responseStatus = xpath.evaluate("//*[local-name()='code']/text()", doc);
String responseText = xpath.evaluate("//*[local-name()='text']/text()", doc);
System.out.println("---> " + responseStatus);
System.out.println("---> " + responseText);
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 .
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
I am in need to create xml as a string to pass to server. I have managed to convert the data into xml but the encoding format set to utf-8 as default. What i need is i want to set it as utf-16 format. But i haven't got any idea of setting it.
private void XmlCreation(int size,List<DataItem> item) throws ParserConfigurationException, TransformerException
{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("ArrayOfDataItem");
document.appendChild(rootElement);
for (DataItem in: item)
{
Element subroot = document.createElement("DataItem");
rootElement.appendChild(subroot);
Element em = document.createElement(in.getKey());
em.appendChild(document.createTextNode(in.getValue()));
subroot.appendChild(em);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
java.io.StringWriter sw = new java.io.StringWriter();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
String xml = sw.toString();
System.out.println(xml);
}
}
Thanks guys
I haven't tested, but that should do the trick:
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-16");
This article might help you. Basically, you call setOutputProperty with OutputKeys.ENCODING as key and the desired encoding ("UTF-16") as value.
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();
}
}