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();
}
}
Related
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);
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);
I've a xml document, which will be used as a template
<?xml version="1.0" encoding="UTF-8" standalone="no"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><content type="application/xml"><m:properties><d:AccountEnabled>true</d:AccountEnabled><d:DisplayName>SampleAppTestj5</d:DisplayName><d:MailNickname>saTestj5</d:MailNickname><d:Password>Qwerty1234</d:Password><d:UserPrincipalName>saTestj5#identropy.us</d:UserPrincipalName></m:properties></content></entry>
I'm calling it in java using this code where payLoadXML.xml has the above content.
"InputStream is = getClass().getClassLoader().getResourceAsStream("/payLoadXML.xml");"
Now I'm trying to edit the tag values for example changing the from "saTestj5" to "saTestj6" and then converting this entire xml and storing it in xml. Can anyone tell me how can I achieve this? I was told this can be done by using "Node" is it possible?
Use jaxb or sax parsers convert into object by using getter method and change the object and convert back to xml
try this
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
docBuilder = docFactory.newDocumentBuilder();
Document doc = null;
InputStream is = getClass().getClassLoader().getResourceAsStream("/payLoadXML.xml");
doc = docBuilder.parse(is);
Node staff = doc.getElementsByTagName("m:properties").item(0);
Text givenNameValue = doc.createTextNode("abc");
Element givenName = doc.createElement("d:GivenName");
givenName.appendChild(givenNameValue);
staff.appendChild(givenName);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Writing to a XML file in Java
I have below XML text as a string.
<someNode>
<id>A124</id>
<status>404</status>
<message>No data</message>
</someNode>
I have above XML data as a String. Is it possible to convert the text into an XML file and archive the generated XML file?
Thanks!
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(theString)));
public class StringToXML {
public static void main(String[] args) {
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"></soap:Envelope>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
// Use String reader
Document document = builder.parse( new InputSource(
new StringReader( xmlString ) ) );
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource( document );
Result dest = new StreamResult( new File( "xmlFileName.xml" ) );
aTransformer.transform( src, dest );
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This information is helpful.
Thanks,
Pavan
Its simple as that:
String text = "<your><xml>data</xml></your>";
Writer writer = new FileWriter("/tmp/filename.xml");
writer.write(text);
writer.flush();
writer.close();
You can, use the java.io.FileWriter to save your file.
String fileData = "<sample><xml>data</xml></sample>";
File outputFile = new File("someFile.xml");
BufferedWriter bw = null;
try{
bw = new BufferedWriter(new FileWriter(outputFile));
bw.write(fileData);
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try{bw.close();}catch(Exception e){}
}
In case you need to manipulate the xml do like Kazekage Gaara said:
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(theString)));
And to save you can do as I said above. To transform the document back to string:
fileData = doc.toString();
I would recommend using commons-io. It has a single method that will do everything you need.
Code would look something like
FileUtils.writeStringToFile(new File("filename.xml"), xml);
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.